Matteo Scandolo | 0f77c50 | 2016-12-06 16:46:00 -0800 | [diff] [blame^] | 1 | /// <reference path="../../../../typings/index.d.ts"/> |
| 2 | |
| 3 | import {Injectable} from '@angular/core'; |
| 4 | import {BehaviorSubject} from 'rxjs/Rx'; |
| 5 | import {IInstance} from '../../interfaces/instance.interface'; |
| 6 | import {InstanceService} from '../rest/instance.service'; |
| 7 | import * as _ from 'lodash'; |
| 8 | import {IWSEvent} from '../../interfaces/ws.interface'; |
| 9 | import {GlobalEvent} from '../websockets/websocket.global'; |
| 10 | |
| 11 | @Injectable() |
| 12 | export class InstanceStore { |
| 13 | private _instances: BehaviorSubject<IInstance[]> = new BehaviorSubject([]); |
| 14 | constructor(private instanceService: InstanceService, private globalEvent: GlobalEvent) { |
| 15 | this.loadInitialData(); |
| 16 | this.globalEvent.list() |
| 17 | .filter((e: IWSEvent) => { |
| 18 | console.log('filter', e); |
| 19 | return e.model === 'Instance'; |
| 20 | }) |
| 21 | .subscribe( |
| 22 | (event: IWSEvent) => { |
| 23 | |
| 24 | const collection = this._instances.value; |
| 25 | |
| 26 | const exist = _.find(collection, (i) => { |
| 27 | return i.id === event.msg.object.id; |
| 28 | }); |
| 29 | |
| 30 | // remove in order to update |
| 31 | if (exist) { |
| 32 | _.remove(collection, {id: event.msg.object.id}); |
| 33 | } |
| 34 | collection.push(event.msg.object); |
| 35 | this._instances.next(collection); |
| 36 | } |
| 37 | ); |
| 38 | } |
| 39 | |
| 40 | loadInitialData() { |
| 41 | this.instanceService.query() |
| 42 | .subscribe( |
| 43 | res => { |
| 44 | this._instances.next(res); |
| 45 | }, |
| 46 | err => console.log('Error retrieving Instances', err) |
| 47 | ); |
| 48 | } |
| 49 | |
| 50 | query() { |
| 51 | return this._instances.asObservable(); |
| 52 | } |
| 53 | |
| 54 | } |