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'; |
Matteo Scandolo | aa024ff | 2017-01-04 15:04:46 -0800 | [diff] [blame] | 4 | import {IXosModelHelpersService} from './model.helpers'; |
| 5 | import {IXosResourceService} from '../rest/model.rest'; |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 6 | |
| 7 | export interface IStoreHelpersService { |
| 8 | updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any>; |
| 9 | } |
| 10 | |
| 11 | export class StoreHelpers { |
Matteo Scandolo | aa024ff | 2017-01-04 15:04:46 -0800 | [diff] [blame] | 12 | static $inject = ['ModelHelpers', 'ModelRest']; |
| 13 | |
| 14 | constructor ( |
| 15 | private modelHelpers: IXosModelHelpersService, |
| 16 | private modelRest: IXosResourceService |
| 17 | ) { |
| 18 | } |
| 19 | |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 20 | public updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any> { |
| 21 | const collection: any[] = subject.value; |
| 22 | const index: number = _.findIndex(collection, (i) => { |
Matteo Scandolo | 63e43eb | 2016-12-14 14:18:53 -0800 | [diff] [blame] | 23 | // NOTE evaluate to use event.msg.pk |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 24 | 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 Scandolo | aa024ff | 2017-01-04 15:04:46 -0800 | [diff] [blame] | 28 | |
| 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 Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 35 | 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 Scandolo | aa024ff | 2017-01-04 15:04:46 -0800 | [diff] [blame] | 40 | collection.splice(index, 1, model); |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 41 | } |
| 42 | // if the element is not deleted add it |
| 43 | else if (!exist && !isDeleted) { |
Matteo Scandolo | aa024ff | 2017-01-04 15:04:46 -0800 | [diff] [blame] | 44 | collection.push(model); |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 45 | } |
| 46 | |
| 47 | subject.next(collection); |
| 48 | |
| 49 | return subject; |
| 50 | } |
| 51 | } |