blob: c26e235875aca192f571dc31a5bb7c08b83c8a87 [file] [log] [blame]
Matteo Scandolo035c5932016-12-14 09:55:15 -08001import {BehaviorSubject} from 'rxjs';
2import * as _ from 'lodash';
Matteo Scandolo04964232017-01-07 12:53:46 -08003import * as pluralize from 'pluralize';
Matteo Scandolo035c5932016-12-14 09:55:15 -08004import {IWSEvent} from '../websocket/global';
Matteo Scandoloaa024ff2017-01-04 15:04:46 -08005import {IXosResourceService} from '../rest/model.rest';
Matteo Scandolo035c5932016-12-14 09:55:15 -08006
7export interface IStoreHelpersService {
Matteo Scandolo04964232017-01-07 12:53:46 -08008 urlFromCoreModel(name: string): string;
Matteo Scandolo035c5932016-12-14 09:55:15 -08009 updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any>;
10}
11
Matteo Scandolo1aee1982017-02-17 08:33:23 -080012export class StoreHelpers implements IStoreHelpersService {
Matteo Scandolo04964232017-01-07 12:53:46 -080013 static $inject = ['ModelRest'];
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080014
15 constructor (
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080016 private modelRest: IXosResourceService
17 ) {
18 }
19
Matteo Scandolo04964232017-01-07 12:53:46 -080020 public urlFromCoreModel(name: string): string {
Matteo Scandolo1aee1982017-02-17 08:33:23 -080021 return `/core/${pluralize(name.toLowerCase())}`;
Matteo Scandolo04964232017-01-07 12:53:46 -080022 }
23
Matteo Scandolo035c5932016-12-14 09:55:15 -080024 public updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any> {
25 const collection: any[] = subject.value;
26 const index: number = _.findIndex(collection, (i) => {
Matteo Scandolo63e43eb2016-12-14 14:18:53 -080027 // NOTE evaluate to use event.msg.pk
Matteo Scandolo035c5932016-12-14 09:55:15 -080028 return i.id === event.msg.object.id;
29 });
30 const exist: boolean = index > -1;
31 const isDeleted: boolean = _.includes(event.msg.changed_fields, 'deleted');
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080032
33 // generate a resource for the model
Matteo Scandolo04964232017-01-07 12:53:46 -080034 const endpoint = this.urlFromCoreModel(event.model);
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080035 const resource = this.modelRest.getResource(endpoint);
36 const model = new resource(event.msg.object);
37
38 // remove
Matteo Scandolo035c5932016-12-14 09:55:15 -080039 if (exist && isDeleted) {
40 _.remove(collection, {id: event.msg.object.id});
41 }
42 // Replace item at index using native splice
43 else if (exist && !isDeleted) {
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080044 collection.splice(index, 1, model);
Matteo Scandolo035c5932016-12-14 09:55:15 -080045 }
46 // if the element is not deleted add it
47 else if (!exist && !isDeleted) {
Matteo Scandoloaa024ff2017-01-04 15:04:46 -080048 collection.push(model);
Matteo Scandolo035c5932016-12-14 09:55:15 -080049 }
50
51 subject.next(collection);
52
53 return subject;
54 }
55}