blob: f31d5715481b75402ecdcc1aedb9f800658e791c [file] [log] [blame]
Matteo Scandolof2c3ed62016-12-15 14:32:50 -08001/// <reference path="../../../../typings/index.d.ts"/>
2
3import {BehaviorSubject, Observable} from 'rxjs/Rx';
4import {IWSEvent, IWSEventService} from '../websocket/global';
5import {IXosResourceService} from '../rest/model.rest';
6import {IStoreHelpersService} from '../helpers/store.helpers';
7
8export interface IModelStoreService {
9 query(model: string): Observable<any>;
10}
11
12export 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}