-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathsocket.service.js
82 lines (71 loc) · 1.97 KB
/
socket.service.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict';
import Primus from './primus';
import primusEmit from 'primus-emit';
import { Injectable } from '@angular/core';
import { noop, find, remove } from 'lodash';
@Injectable()
export class SocketService {
primus;
constructor() {
const primus = Primus.connect();
primus.plugin('emit', primusEmit);
primus.on('open', function open() {
console.log('Connection opened');
});
if(process.env.NODE_ENV === 'development') {
primus.on('data', function message(data) {
console.log('Socket:', data);
});
}
primus.on('info', data => {
console.log('info:', data);
});
this.primus = primus;
}
/**
* Register listeners to sync an array with updates on a model
*
* Takes the array we want to sync, the model name that socket updates are sent from,
* and an optional callback function after new items are updated.
*
* @param {String} modelName
* @param {Array} array
* @param {Function} cb
*/
syncUpdates(modelName, array, cb = noop) {
/**
* Syncs item creation/updates on 'model:save'
*/
this.primus.on(`${modelName}:save`, item => {
console.log(item);
let oldItem = find(array, {_id: item._id});
let index = array.indexOf(oldItem);
let event = 'created';
// replace oldItem if it exists
// otherwise just add item to the collection
if(oldItem) {
array.splice(index, 1, item);
event = 'updated';
} else {
array.push(item);
}
cb(event, item, array);
});
/**
* Syncs removed items on 'model:remove'
*/
this.primus.on(`${modelName}:remove`, item => {
remove(array, {_id: item._id});
cb('deleted', item, array);
});
}
/**
* Removes listeners for a models updates on the socket
*
* @param modelName
*/
unsyncUpdates(modelName) {
this.primus.removeAllListeners(`${modelName}:save`);
this.primus.removeAllListeners(`${modelName}:remove`);
}
}