Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 1 | /// <reference path="../../../../typings/index.d.ts"/> |
| 2 | |
| 3 | import {BehaviorSubject, Observable} from 'rxjs/Rx'; |
| 4 | import {IWSEvent, IWSEventService} from '../websocket/global'; |
| 5 | import {IXosResourceService} from '../rest/model.rest'; |
| 6 | import {IStoreHelpersService} from '../helpers/store.helpers'; |
| 7 | |
| 8 | export interface IModelStoreService { |
| 9 | query(model: string): Observable<any>; |
| 10 | } |
| 11 | |
| 12 | export class ModelStore { |
| 13 | static $inject = ['WebSocket', 'StoreHelpers', 'ModelRest']; |
| 14 | private _slices: BehaviorSubject<any[]> = new BehaviorSubject([]); |
| 15 | constructor( |
| 16 | private webSocket: IWSEventService, |
| 17 | private storeHelpers: IStoreHelpersService, |
| 18 | private sliceService: IXosResourceService |
| 19 | ) { |
| 20 | } |
| 21 | |
| 22 | query(model: string) { |
| 23 | this.loadInitialData(model); |
| 24 | this.webSocket.list() |
| 25 | .filter((e: IWSEvent) => e.model === model) |
| 26 | .subscribe( |
| 27 | (event: IWSEvent) => { |
| 28 | this.storeHelpers.updateCollection(event, this._slices); |
| 29 | } |
| 30 | ); |
| 31 | return this._slices.asObservable(); |
| 32 | } |
| 33 | |
| 34 | private loadInitialData(model: string) { |
| 35 | const endpoint = `/core/${model.toLowerCase()}s/`; |
| 36 | this.sliceService.getResource(endpoint).query().$promise |
| 37 | .then( |
| 38 | res => { |
| 39 | this._slices.next(res); |
| 40 | }, |
| 41 | err => console.log(`Error retrieving ${model}`, err) |
| 42 | ); |
| 43 | } |
| 44 | } |