Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 1 | import {BehaviorSubject} from 'rxjs'; |
| 2 | import * as _ from 'lodash'; |
| 3 | import {IWSEvent} from '../websocket/global'; |
| 4 | |
| 5 | export interface IStoreHelpersService { |
| 6 | updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any>; |
| 7 | } |
| 8 | |
| 9 | export 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) => { |
Matteo Scandolo | 63e43eb | 2016-12-14 14:18:53 -0800 | [diff] [blame] | 13 | // NOTE evaluate to use event.msg.pk |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 14 | return i.id === event.msg.object.id; |
| 15 | }); |
| 16 | const exist: boolean = index > -1; |
| 17 | const isDeleted: boolean = _.includes(event.msg.changed_fields, 'deleted'); |
| 18 | // remove |
| 19 | if (exist && isDeleted) { |
| 20 | _.remove(collection, {id: event.msg.object.id}); |
| 21 | } |
| 22 | // Replace item at index using native splice |
| 23 | else if (exist && !isDeleted) { |
| 24 | collection.splice(index, 1, event.msg.object); |
| 25 | } |
| 26 | // if the element is not deleted add it |
| 27 | else if (!exist && !isDeleted) { |
| 28 | collection.push(event.msg.object); |
| 29 | } |
| 30 | |
| 31 | subject.next(collection); |
| 32 | |
| 33 | return subject; |
| 34 | } |
| 35 | } |