blob: 903bd46fdca8f63a22d93f4b1661448093902d5c [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 Scandolof9dd4d02016-12-22 15:17:01 -080014 private _collections: any; // NOTE contains a map of {model: BehaviourSubject}
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 ) {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080020 this._collections = {};
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080021 }
22
23 query(model: string) {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080024
25 // if there isn't already an observable for that item
26 if (!this._collections[model]) {
27 this._collections[model] = new BehaviorSubject([]); // NOTE maybe this can be created when we get response from the resource
28 this.loadInitialData(model);
29 }
30
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080031 this.webSocket.list()
32 .filter((e: IWSEvent) => e.model === model)
33 .subscribe(
34 (event: IWSEvent) => {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080035 this.storeHelpers.updateCollection(event, this._collections[model]);
Matteo Scandoloa4a47112016-12-16 10:06:13 -080036 },
37 err => console.error
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080038 );
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080039
40 return this._collections[model].asObservable();
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080041 }
42
43 private loadInitialData(model: string) {
Matteo Scandoloee655a12016-12-19 15:38:43 -080044 // NOTE check what is the correct pattern to pluralize this
45 const endpoint = `/core/${model.toLowerCase()}s`;
Matteo Scandoloa4a47112016-12-16 10:06:13 -080046 this.ModelRest.getResource(endpoint).query().$promise
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080047 .then(
48 res => {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080049 this._collections[model].next(res);
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080050 },
51 err => console.log(`Error retrieving ${model}`, err)
52 );
53 }
54}