-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathIrisClientSubscription.js
71 lines (55 loc) · 1.62 KB
/
IrisClientSubscription.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
const crypto = typeof (window) !== 'undefined' && window.crypto ? window.crypto : require('isomorphic-webcrypto')
class IrisClientSubscription {
constructor(channel, topic, handler, id) {
this.channel = channel
this.topic = topic
this.handler = handler
this.id = id ? id : this.createId()
this.gotResponse = false
}
static actionSubscription(contract, action, handler) {
return new IrisClientSubscription(Channels.ACTION, `${contract}::${action}`, handler)
}
static transferSubscription(account, handler) {
return new IrisClientSubscription(Channels.TRANSFER, account, handler)
}
createId() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}
responseReceived() {
this.gotResponse = true
}
setHandler(handler) {
this.handler = handler
}
getChannel() {
return this.channel
}
getTopic() {
return this.topic
}
handle(message) {
this.handler(message)
}
getId() {
return this.id
}
static fromObj(obj) {
if (typeof obj === 'string')
obj = JSON.parse(obj)
return new IrisClientSubscription(obj.channel, obj.topic, obj.handler, obj.id)
}
isValid() {
return this.channel && this.topic && this.id
}
toJSON() {
return JSON.stringify({
channel: this.channel,
topic: this.topic,
id: this.id
})
}
}
module.exports = IrisClientSubscription