-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathsocket.service.js
68 lines (61 loc) · 1.81 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
'use strict';
import { Injectable } from '@angular/core';
import { noop, find, remove } from 'lodash';
import io from 'socket.io-client';
import constants from '../../app/app.constants';
@Injectable()
export class SocketService {
socket;
constructor() {
this.socket = io(constants.env === 'development' ? `localhost:${constants.port}` : '', {
// Send auth token on connection, you will need to DI the Auth service above
// 'query': 'token=' + Auth.getToken()
});
}
/**
* 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.socket.on(`${modelName}:save`, function(item) {
var oldItem = find(array, {_id: item._id});
var index = array.indexOf(oldItem);
var 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.socket.on(`${modelName}:remove`, function(item) {
var event = 'deleted';
remove(array, {_id: item._id});
cb(event, item, array);
});
}
/**
* Removes listeners for a models updates on the socket
*
* @param modelName
*/
unsyncUpdates(modelName) {
this.socket.removeAllListeners(`${modelName}:save`);
this.socket.removeAllListeners(`${modelName}:remove`);
}
}