blob: dfb1e7ae4de41a5ff017f58e646c3f3c0258aa6b [file] [log] [blame]
Matteo Scandolo035c5932016-12-14 09:55:15 -08001import {BehaviorSubject} from 'rxjs';
2import * as _ from 'lodash';
3import {IWSEvent} from '../websocket/global';
4
5export interface IStoreHelpersService {
6 updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any>;
7}
8
9export class StoreHelpers {
10 public updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any> {
11 const collection: any[] = subject.value;
12 const index: number = _.findIndex(collection, (i) => {
13 return i.id === event.msg.object.id;
14 });
15 const exist: boolean = index > -1;
16 const isDeleted: boolean = _.includes(event.msg.changed_fields, 'deleted');
17 // remove
18 if (exist && isDeleted) {
19 _.remove(collection, {id: event.msg.object.id});
20 }
21 // Replace item at index using native splice
22 else if (exist && !isDeleted) {
23 collection.splice(index, 1, event.msg.object);
24 }
25 // if the element is not deleted add it
26 else if (!exist && !isDeleted) {
27 collection.push(event.msg.object);
28 }
29
30 subject.next(collection);
31
32 return subject;
33 }
34}