blob: 1458d816f31143bd11e972b9060be75d2a73b2b4 [file] [log] [blame]
Matteo Scandolo035c5932016-12-14 09:55:15 -08001import {BehaviorSubject} from 'rxjs';
2import * as _ from 'lodash';
3import {IWSEvent} from '../websocket/global';
Matteo Scandoloaa024ff2017-01-04 15:04:46 -08004import {IXosResourceService} from '../rest/model.rest';
Matteo Scandolo1c5905f2017-01-04 17:41:15 -08005import {IXosConfigHelpersService} from '../../core/services/helpers/config.helpers';
Matteo Scandolo035c5932016-12-14 09:55:15 -08006
7export interface IStoreHelpersService {
8 updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any>;
9}
10
11export class StoreHelpers {
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080012 static $inject = ['ConfigHelpers', 'ModelRest'];
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080013
14 constructor (
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080015 private configHelpers: IXosConfigHelpersService,
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080016 private modelRest: IXosResourceService
17 ) {
18 }
19
Matteo Scandolo035c5932016-12-14 09:55:15 -080020 public updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any> {
21 const collection: any[] = subject.value;
22 const index: number = _.findIndex(collection, (i) => {
Matteo Scandolo63e43eb2016-12-14 14:18:53 -080023 // NOTE evaluate to use event.msg.pk
Matteo Scandolo035c5932016-12-14 09:55:15 -080024 return i.id === event.msg.object.id;
25 });
26 const exist: boolean = index > -1;
27 const isDeleted: boolean = _.includes(event.msg.changed_fields, 'deleted');
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080028
29 // generate a resource for the model
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080030 const endpoint = this.configHelpers.urlFromCoreModel(event.model);
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080031 const resource = this.modelRest.getResource(endpoint);
32 const model = new resource(event.msg.object);
33
34 // remove
Matteo Scandolo035c5932016-12-14 09:55:15 -080035 if (exist && isDeleted) {
36 _.remove(collection, {id: event.msg.object.id});
37 }
38 // Replace item at index using native splice
39 else if (exist && !isDeleted) {
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080040 collection.splice(index, 1, model);
Matteo Scandolo035c5932016-12-14 09:55:15 -080041 }
42 // if the element is not deleted add it
43 else if (!exist && !isDeleted) {
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080044 collection.push(model);
Matteo Scandolo035c5932016-12-14 09:55:15 -080045 }
46
47 subject.next(collection);
48
49 return subject;
50 }
51}