import { Injectable } from '@angular/core' ; import { v4 } from 'uuid' ; import { FileElement } from '../file-explorer/model/element' ; import { BehaviorSubject } from 'rxjs/BehaviorSubject' ; import { Observable } from 'rxjs/Observable' ; export interface IFileService { add ( fileElement ) ; delete ( id ) ; update ( id , update ) ; queryInFolder ( folderId ) : Observable < FileElement [ ] > ; get ( id ) : FileElement ; } @ Injectable ( ) export class FileService implements IFileService { private map = new Map < string , FileElement > ( ) ; constructor ( ) { } add ( fileElement ) { fileElement . id = v4 ( ) ; this . map . set ( fileElement . id , this . clone ( fileElement ) ) ; return fileElement ; } delete ( id ) { this . map . delete ( id ) ; } update ( id , update ) { let element = this . map . get ( id ) ; element = Object . assign ( element , update ) ; this . map . set ( element . id , element ) ; } private querySubject : BehaviorSubject < FileElement [ ] > ; queryInFolder ( folderId ) { const result = [ ] ; this . map . forEach ( element => { if ( element . parent === folderId ) { result . push ( this . clone ( element ) ) ; } } ) ; if ( ! this . querySubject ) { this . querySubject = new BehaviorSubject ( result ) ; } else { this . querySubject . next ( result ) ; } return this . querySubject . asObservable ( ) ; } get ( id ) { return this . map . get ( id ) ; } clone ( element ) { return JSON . parse ( JSON . stringify ( element ) ) ; } }