blob: 34e2951e89a3d5bcd4e09438a0b3d416664faae2 [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';
Matteo Scandoloaa024ff2017-01-04 15:04:46 -08007import {IXosModelHelpersService} from '../helpers/model.helpers';
Matteo Scandolof2c3ed62016-12-15 14:32:50 -08008
9export interface IModelStoreService {
10 query(model: string): Observable<any>;
11}
12
13export class ModelStore {
Matteo Scandolobac22452017-01-03 16:35:32 -080014 static $inject = ['WebSocket', 'StoreHelpers', 'ModelRest', 'ModelHelpers'];
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080015 private _collections: any; // NOTE contains a map of {model: BehaviourSubject}
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080016 constructor(
17 private webSocket: IWSEventService,
18 private storeHelpers: IStoreHelpersService,
Matteo Scandolobac22452017-01-03 16:35:32 -080019 private ModelRest: IXosResourceService,
20 private ModelHelpers: IXosModelHelpersService
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080021 ) {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080022 this._collections = {};
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080023 }
24
25 query(model: string) {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080026 // if there isn't already an observable for that item
27 if (!this._collections[model]) {
28 this._collections[model] = new BehaviorSubject([]); // NOTE maybe this can be created when we get response from the resource
29 this.loadInitialData(model);
30 }
31
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080032 this.webSocket.list()
33 .filter((e: IWSEvent) => e.model === model)
34 .subscribe(
35 (event: IWSEvent) => {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080036 this.storeHelpers.updateCollection(event, this._collections[model]);
Matteo Scandoloa4a47112016-12-16 10:06:13 -080037 },
38 err => console.error
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080039 );
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080040
41 return this._collections[model].asObservable();
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080042 }
43
44 private loadInitialData(model: string) {
Matteo Scandoloee655a12016-12-19 15:38:43 -080045 // NOTE check what is the correct pattern to pluralize this
Matteo Scandolobac22452017-01-03 16:35:32 -080046 const endpoint = this.ModelHelpers.urlFromCoreModel(model);
Matteo Scandoloa4a47112016-12-16 10:06:13 -080047 this.ModelRest.getResource(endpoint).query().$promise
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080048 .then(
49 res => {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080050 this._collections[model].next(res);
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080051 },
52 err => console.log(`Error retrieving ${model}`, err)
53 );
54 }
55}