-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
184 lines (158 loc) · 4.41 KB
/
index.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// Import our required packages.
const nostrEmitter = (typeof window !== 'undefined')
? window.NostrEmitter
: require('@cmdcode/nostr-emitter')
const now = () => Math.floor(Date.now() / 1000)
// const { Hash, getRandomString } = nostrEmitter.utils
class NostrStore {
static DEFAULT_OPT = {
emitter: {},
refreshTimeout: 5000,
commitTimeout: 5000
}
static DEFAULT_EMIT_OPT = {
kind: 10001, // Replaceable events.
since: null, // We want all historical events.
selfPub: true, // We want our own events.
}
static encode(key, value) {
// Convert non-standard javascript objects to json.
if (value instanceof Map)
return { type: 'Map', value: [ ...value ] }
if (value instanceof Date)
return { type: 'Date', value: value }
return value;
}
static decode(key, value) {
// Convert non-standard json objects to javascript.
if (typeof value === 'object' && value !== null) {
if (value.type === 'Map') return new Map(value.value)
if (value.type === 'Date') return new Date(value.value)
}
return value;
}
constructor(opt = {}) {
// Configure our store object.
this.data = new Map()
this.storeId = null
this.init = false
this.connected = false
this.opt = { ...NostrStore.DEFAULT_OPT, ...opt }
this.log = str => (opt.log) ? opt.log(str) : console.log(str)
// Configure our underlying emitter object.
this.emitter = new nostrEmitter({
...NostrStore.DEFAULT_EMIT_OPT,
...this.opt.emitter
})
// Our main event handler.
this.emitter.on('all', (data, meta) => {
// Check that we have data in the proper format.
if (data && typeof data === 'string') {
this.data = JSON.parse(data, NostrStore.decode)
this.storeId = meta.id
}
// Else, check if we need to initialize.
else if (!this.init) {
this.data = new Map()
this.init = true
}
// Else, something is wrong.
else {
this.log('Invalid data:', data)
}
// Update our internal timestamp.
this.lastUpdate = now()
})
}
async connect(relayUrl, secret) {
// Pass the url to the emitter.
this.emitter.relayUrl = relayUrl;
// Use the secret for generating the signing key.
this.emitter.signSecret = secret;
// Use a hashed version of the secret to encrypt the data.
this.emitter.secret = await Hash.from(secret).toHex()
// Connect to the relay.
return this.emitter.connect().then(() => this.connected = this.emitter.connected)
}
hasExpired() {
// Check if our data store has expired.
const { refreshTimeout } = this.opt
return (now() - this.lastUpdate) > refreshTimeout
}
async refresh() {
// If the data is stale, resub to the relay.
if (this.hasExpired()) {
await this.emitter.subscribe()
}
}
async commit() {
// Commit our data to the relay.
const { commitTimeout } = this.opt
const commitId = getRandomString(16)
const encoded = JSON.stringify(this.data, NostrStore.encode)
return new Promise((res, rej) => {
setTimeout(() => res(null), commitTimeout)
this.emitter.within(commitId, (data) => {
return (data === encoded)
? res(this.data)
: res(null)
}, commitTimeout)
this.emitter.emit(commitId, encoded)
})
}
async has(key) {
await this.refresh()
return (this.data.get(key) === true)
}
async get(key) {
await this.refresh()
return this.data.get(key)
}
async set(key, value) {
if (this.data.get(key) === value) {
return this.data
}
this.data.set(key, value)
return this.commit()
}
async delete(key) {
this.data.delete(key)
return this.commit()
}
async clear() {
this.data = new Map()
return this.commit()
}
async destroy() {
await this.refresh()
await this.clear()
if (this.storeId) {
this.emitter.emit('destroy', '', {
kind: 5,
tags: [['e', this.storeId ]]
})
}
return null
}
keys() {
return this.data.keys()
}
values() {
return this.data.values()
}
entries() {
return this.data.entries()
}
toString() {
return JSON.stringify(this.data, null, 2)
}
[Symbol.iterator]() {
return this.data[Symbol.iterator]()
}
}
// Handle exports between browser and node.
if (typeof window !== 'undefined') {
window.NostrStore = NostrStore
} else {
module.exports = NostrStore
}