blob: 7e5dad740449fd842e15a64c30062d412902ebb0 [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 Scandoloe015fa92017-05-10 09:52:36 -070026
Matteo Scandolo035c5932016-12-14 09:55:15 -080027 private _events: Subject<IWSEvent> = new Subject<IWSEvent>();
Matteo Scandoloe015fa92017-05-10 09:52:36 -070028 private socket;
29 constructor(
30 private AppConfig: IXosAppConfig,
31 private $log: ng.ILogService
32 ) {
33 // NOTE list of field that are not useful to the UI
34 const ignoredFields: string[] = ['created', 'updated', 'backend_register'];
Matteo Scandolo98b5f5d2017-03-17 17:09:05 -070035
Matteo Scandoloe015fa92017-05-10 09:52:36 -070036 this.socket = io(this.AppConfig.websocketClient);
37 this.socket.on('event', (data: IWSEvent): void => {
38 this.$log.debug(`[WebSocket] Received Event for: ${data.model} [${data.msg.pk}]`);
Matteo Scandolo98b5f5d2017-03-17 17:09:05 -070039
Matteo Scandoloe015fa92017-05-10 09:52:36 -070040 if (data.msg.changed_fields.length === 0 || _.intersection(data.msg.changed_fields, ignoredFields).length === data.msg.changed_fields.length) {
41 // NOTE means that the only updated fields does not change anything in the UI, so don't send events around
42 this.$log.debug(`[WebSocket] Ignoring Event for: ${data.model} [${data.msg.pk}]`);
43 return;
44 }
45
46 this._events.next(data);
47
48 // NOTE update observers of parent classes
49 if (data.msg.object.class_names && angular.isString(data.msg.object.class_names)) {
50 const models = data.msg.object.class_names.split(',');
51 _.forEach(models, (m: string) => {
52 data.model = m;
53 this._events.next(data);
54 });
55 }
56
57 });
Matteo Scandolo035c5932016-12-14 09:55:15 -080058 }
59 list() {
60 return this._events.asObservable();
61 }
62}