-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathNostrClient.js
More file actions
87 lines (75 loc) · 2.13 KB
/
NostrClient.js
File metadata and controls
87 lines (75 loc) · 2.13 KB
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
import RelayPool from 'src/nostr/RelayPool'
import {CloseAfter} from 'src/nostr/Relay'
export default class NostrClient {
constructor(relays) {
this.pool = new RelayPool(relays)
this.pool.on('notice', this.onNotice.bind(this))
this.pool.on('ok', this.onOk.bind(this))
window.clientSubscribe = this.subscribe.bind(this)
}
connect() {
this.pool.connect()
}
disconnect() {
this.pool.disconnect()
}
connectedRelays() {
return this.pool.connectedRelays()
}
isConnectedTo(url) {
// TODO remove linear scan
return this.connectedRelays().some(relay => relay.url === url)
}
subscribe(filters, subId = null, closeAfter = CloseAfter.NEVER) {
return this.pool.subscribe(filters, subId, closeAfter)
}
unsubscribe(subId) {
this.pool.unsubscribe(subId)
}
publish(event) {
return this.pool.publish(event)
}
fetch(filters, opts = {}) {
return new Promise(resolve => {
const events = {}
const sub = this.pool.subscribe(filters, opts.subId, CloseAfter.EOSE)
const timer = setTimeout(() => {
sub.close()
resolve(Object.values(events))
}, opts.timeout || 4000)
sub.on('event', event => {
events[event.id] = event
})
sub.on('end', () => {
sub.close()
clearTimeout(timer)
resolve(Object.values(events))
})
sub.on('close', () => {
clearTimeout(timer)
resolve(Object.values(events))
})
})
}
stream(filters, eventCallback, endCallback = () => {}, opts = {}) {
const events = {}
const sub = this.pool.subscribe(filters, opts.subId)
const timer = setTimeout(() => {
endCallback(Object.values(events))
}, opts.timeout || 4000)
sub.on('event', event => {
events[event.id] = event
})
sub.on('end', () => {
clearTimeout(timer)
endCallback(Object.values(events))
})
return sub
}
onNotice(relay, message) {
console.warn(`[NOTICE] from ${relay}: ${message}`)
}
onOk(relay, eventId, wasSaved, message) {
console.log(`[OK] from ${relay}: eventId=${eventId}, wasSaved=${wasSaved}, message=${message}`)
}
}