blob: fdcac634b1b559dd096b33e9fe4b47e35848ec00 [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 {
Matteo Scandolo04964232017-01-07 12:53:46 -080013 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 Scandolobac22452017-01-03 16:35:32 -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
Matteo Scandolo04964232017-01-07 12:53:46 -080023 public query(model: string) {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080024 // if there isn't already an observable for that item
25 if (!this._collections[model]) {
26 this._collections[model] = new BehaviorSubject([]); // NOTE maybe this can be created when we get response from the resource
27 this.loadInitialData(model);
28 }
29
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080030 this.webSocket.list()
31 .filter((e: IWSEvent) => e.model === model)
32 .subscribe(
33 (event: IWSEvent) => {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080034 this.storeHelpers.updateCollection(event, this._collections[model]);
Matteo Scandoloa4a47112016-12-16 10:06:13 -080035 },
36 err => console.error
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080037 );
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080038
39 return this._collections[model].asObservable();
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080040 }
41
Matteo Scandolo04964232017-01-07 12:53:46 -080042 public get(model: string, id: number) {
43 // TODO implement a get method
44 }
45
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080046 private loadInitialData(model: string) {
Matteo Scandoloee655a12016-12-19 15:38:43 -080047 // NOTE check what is the correct pattern to pluralize this
Matteo Scandolo04964232017-01-07 12:53:46 -080048 const endpoint = this.storeHelpers.urlFromCoreModel(model);
Matteo Scandoloa4a47112016-12-16 10:06:13 -080049 this.ModelRest.getResource(endpoint).query().$promise
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080050 .then(
51 res => {
Matteo Scandolof9dd4d02016-12-22 15:17:01 -080052 this._collections[model].next(res);
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080053 },
54 err => console.log(`Error retrieving ${model}`, err)
55 );
56 }
57}