blob: a8202699046fc201afc1c0d2269bc6aa4e1457c1 [file] [log] [blame]
Matteo Scandolo035c5932016-12-14 09:55:15 -08001import * as io from 'socket.io-client';
Matteo Scandolo98b5f5d2017-03-17 17:09:05 -07002import * as _ from 'lodash';
Matteo Scandolo035c5932016-12-14 09:55:15 -08003import {Subject, Observable} from 'rxjs/Rx';
Matteo Scandolo828d1e82017-01-17 14:49:38 -08004import {IXosAppConfig} from '../../../index';
Matteo Scandolo035c5932016-12-14 09:55:15 -08005
6export interface IWSEvent {
7 model: string;
8 msg: {
9 changed_fields: string[],
10 object?: any,
11 pk?: number
12 };
13}
14
15export interface IWSEventService {
16 list(): Observable<IWSEvent>;
17}
18
19export class WebSocketEvent {
Matteo Scandolo828d1e82017-01-17 14:49:38 -080020
Matteo Scandolo98b5f5d2017-03-17 17:09:05 -070021 static $inject = [
22 'AppConfig',
23 '$log'
24 ];
Matteo Scandolo828d1e82017-01-17 14:49:38 -080025
Matteo Scandolo035c5932016-12-14 09:55:15 -080026 private _events: Subject<IWSEvent> = new Subject<IWSEvent>();
27 private socket;
Matteo Scandolo828d1e82017-01-17 14:49:38 -080028 constructor(
Matteo Scandolo98b5f5d2017-03-17 17:09:05 -070029 private AppConfig: IXosAppConfig,
30 private $log: ng.ILogService
Matteo Scandolo828d1e82017-01-17 14:49:38 -080031 ) {
32 this.socket = io(this.AppConfig.websocketClient);
Matteo Scandolo035c5932016-12-14 09:55:15 -080033 this.socket.on('event', (data: IWSEvent): void => {
Matteo Scandolo98b5f5d2017-03-17 17:09:05 -070034 this.$log.debug(`[WebSocket] Received Event for: ${data.model} [${data.msg.pk}]`);
Matteo Scandolo035c5932016-12-14 09:55:15 -080035 this._events.next(data);
Matteo Scandolo98b5f5d2017-03-17 17:09:05 -070036
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 Scandolo035c5932016-12-14 09:55:15 -080046 });
47 }
48 list() {
49 return this._events.asObservable();
50 }
51}