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']; |
Matteo Scandolo | a4a4711 | 2016-12-16 10:06:13 -0800 | [diff] [blame^] | 14 | private _collection: BehaviorSubject<any[]> = new BehaviorSubject([]); |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 15 | constructor( |
| 16 | private webSocket: IWSEventService, |
| 17 | private storeHelpers: IStoreHelpersService, |
Matteo Scandolo | a4a4711 | 2016-12-16 10:06:13 -0800 | [diff] [blame^] | 18 | private ModelRest: IXosResourceService |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 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) => { |
Matteo Scandolo | a4a4711 | 2016-12-16 10:06:13 -0800 | [diff] [blame^] | 28 | this.storeHelpers.updateCollection(event, this._collection); |
| 29 | }, |
| 30 | err => console.error |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 31 | ); |
Matteo Scandolo | a4a4711 | 2016-12-16 10:06:13 -0800 | [diff] [blame^] | 32 | return this._collection.asObservable(); |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 33 | } |
| 34 | |
| 35 | private loadInitialData(model: string) { |
| 36 | const endpoint = `/core/${model.toLowerCase()}s/`; |
Matteo Scandolo | a4a4711 | 2016-12-16 10:06:13 -0800 | [diff] [blame^] | 37 | this.ModelRest.getResource(endpoint).query().$promise |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 38 | .then( |
| 39 | res => { |
Matteo Scandolo | a4a4711 | 2016-12-16 10:06:13 -0800 | [diff] [blame^] | 40 | this._collection.next(res); |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 41 | }, |
| 42 | err => console.log(`Error retrieving ${model}`, err) |
| 43 | ); |
| 44 | } |
| 45 | } |