Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 1 | import * as io from 'socket.io-client'; |
Matteo Scandolo | 98b5f5d | 2017-03-17 17:09:05 -0700 | [diff] [blame] | 2 | import * as _ from 'lodash'; |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 3 | import {Subject, Observable} from 'rxjs/Rx'; |
Matteo Scandolo | 828d1e8 | 2017-01-17 14:49:38 -0800 | [diff] [blame] | 4 | import {IXosAppConfig} from '../../../index'; |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 5 | |
| 6 | export interface IWSEvent { |
| 7 | model: string; |
| 8 | msg: { |
| 9 | changed_fields: string[], |
| 10 | object?: any, |
| 11 | pk?: number |
| 12 | }; |
| 13 | } |
| 14 | |
| 15 | export interface IWSEventService { |
| 16 | list(): Observable<IWSEvent>; |
| 17 | } |
| 18 | |
| 19 | export class WebSocketEvent { |
Matteo Scandolo | 828d1e8 | 2017-01-17 14:49:38 -0800 | [diff] [blame] | 20 | |
Matteo Scandolo | 98b5f5d | 2017-03-17 17:09:05 -0700 | [diff] [blame] | 21 | static $inject = [ |
| 22 | 'AppConfig', |
| 23 | '$log' |
| 24 | ]; |
Matteo Scandolo | 828d1e8 | 2017-01-17 14:49:38 -0800 | [diff] [blame] | 25 | |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 26 | private _events: Subject<IWSEvent> = new Subject<IWSEvent>(); |
| 27 | private socket; |
Matteo Scandolo | 828d1e8 | 2017-01-17 14:49:38 -0800 | [diff] [blame] | 28 | constructor( |
Matteo Scandolo | 98b5f5d | 2017-03-17 17:09:05 -0700 | [diff] [blame] | 29 | private AppConfig: IXosAppConfig, |
| 30 | private $log: ng.ILogService |
Matteo Scandolo | 828d1e8 | 2017-01-17 14:49:38 -0800 | [diff] [blame] | 31 | ) { |
| 32 | this.socket = io(this.AppConfig.websocketClient); |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 33 | this.socket.on('event', (data: IWSEvent): void => { |
Matteo Scandolo | 98b5f5d | 2017-03-17 17:09:05 -0700 | [diff] [blame] | 34 | this.$log.debug(`[WebSocket] Received Event for: ${data.model} [${data.msg.pk}]`); |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 35 | this._events.next(data); |
Matteo Scandolo | 98b5f5d | 2017-03-17 17:09:05 -0700 | [diff] [blame] | 36 | |
| 37 | // NOTE update observers of parent classes |
| 38 | if (data.msg.object.class_names && angular.isString(data.msg.object.class_names)) { |
| 39 | const models = data.msg.object.class_names.split(','); |
| 40 | _.forEach(models, (m: string) => { |
| 41 | data.model = m; |
| 42 | this._events.next(data); |
| 43 | }); |
| 44 | } |
| 45 | |
Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 46 | }); |
| 47 | } |
| 48 | list() { |
| 49 | return this._events.asObservable(); |
| 50 | } |
| 51 | } |