blob: d306f9d55a67c63c9a65b27efbf87d43324bd9f6 [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'];
Matteo Scandoloa4a47112016-12-16 10:06:13 -080014 private _collection: BehaviorSubject<any[]> = new BehaviorSubject([]);
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080015 constructor(
16 private webSocket: IWSEventService,
17 private storeHelpers: IStoreHelpersService,
Matteo Scandoloa4a47112016-12-16 10:06:13 -080018 private ModelRest: IXosResourceService
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080019 ) {
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 Scandoloa4a47112016-12-16 10:06:13 -080028 this.storeHelpers.updateCollection(event, this._collection);
29 },
30 err => console.error
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080031 );
Matteo Scandoloa4a47112016-12-16 10:06:13 -080032 return this._collection.asObservable();
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080033 }
34
35 private loadInitialData(model: string) {
36 const endpoint = `/core/${model.toLowerCase()}s/`;
Matteo Scandoloa4a47112016-12-16 10:06:13 -080037 this.ModelRest.getResource(endpoint).query().$promise
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080038 .then(
39 res => {
Matteo Scandoloa4a47112016-12-16 10:06:13 -080040 this._collection.next(res);
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080041 },
42 err => console.log(`Error retrieving ${model}`, err)
43 );
44 }
45}