blob: 99662dab08965ca6d524786633351a45ec690169 [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 {IXosModelHelpersService} from './model.helpers';
5import {IXosResourceService} from '../rest/model.rest';
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 Scandoloaa024ff2017-01-04 15:04:46 -080012 static $inject = ['ModelHelpers', 'ModelRest'];
13
14 constructor (
15 private modelHelpers: IXosModelHelpersService,
16 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
30 const endpoint = this.modelHelpers.urlFromCoreModel(event.model);
31 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}