forked from tidev/titanium-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
appcd.js
88 lines (83 loc) · 1.78 KB
/
appcd.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
83
84
85
86
87
88
const EventEmitter = require('events');
/**
* Creates a simplified promise-based client for Appcd
*
* @param {object} client A appcd-client instance
* @return {object} Promisified wrapper around appcd-client
*/
const appcd = (client) => ({
host: client.host,
port: client.port,
async connect(options) {
return new Promise((resolve, reject) => {
client.connect(options)
.once('connected', resolve)
.once('error', reject);
});
},
disconnect() {
client.disconnect();
},
async get(path) {
return this.request({ path });
},
async post(path, data = {}) {
return this.request({ path, data });
},
async request(options) {
return new Promise((resolve, reject) => {
client
.request(options)
.once('response', response => resolve(response))
.once('error', e => reject(e));
});
},
async subscribe(path) {
return new Promise((resolve, reject) => {
const subscription = new Subscription(path);
client
.request({
path,
type: 'subscribe'
})
.on('response', (data, response) => {
if (typeof data === 'string' && data === 'Subscribed') {
subscription.sid = response.sid;
return resolve(subscription);
}
subscription.emit('message', data);
})
.once('close', () => {
subscription.emit('close');
})
.once('finish', () => {
subscription.emit('close');
})
.once('error', e => {
if (!subscription.sid) {
reject(e);
} else {
subscription.emit('error', e);
}
});
});
}
});
class Subscription extends EventEmitter {
constructor(path) {
super();
this.path = path;
this.sid = null;
}
async unsubscribe() {
if (!this.sid) {
return;
}
await appcd.request({
path: this.path,
sid: this.sid
});
this.sid = null;
}
}
module.exports = appcd;