-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.js
47 lines (37 loc) · 1.23 KB
/
socket.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
const WebSocket = require('ws');
class Socket {
constructor({ accessKey, secretKey, host, projectId, onServiceUpgrade }) {
this.url = ''
+ 'wss://'
+ `${accessKey}:${secretKey}@${host}`
+ '/v2-beta/projects/'
+ `${projectId}`
+ '/subscribe?eventNames=resource.change';
this.onMessage = this.onMessage.bind(this);
this.onOpen = this.onOpen.bind(this);
this.onClose = this.onClose.bind(this);
this.onServiceUpgrade = onServiceUpgrade;
}
connect() {
this.socket = new WebSocket(this.url);
this.socket.on('open', this.onOpen);
this.socket.on('message', this.onMessage);
this.socket.on('close', this.onClose);
}
onMessage(messageStr) {
const message = JSON.parse(messageStr);
if (message.name === 'resource.change' && message.data) {
const resource = message.data.resource;
if (resource.eventType === 'service.finishupgrade') {
this.onServiceUpgrade(resource.serviceId);
}
}
}
onOpen() {
console.log('Socket opened');
}
onClose() {
console.log('Socket closed');
}
}
module.exports = Socket;