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) => { |
| 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 | } |