-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathflash-store.ts
366 lines (315 loc) · 9.25 KB
/
flash-store.ts
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import rimraf from 'rimraf'
// import encoding from 'encoding-down'
// import leveldown from 'leveldown'
// import levelup from 'levelup'
import level from 'level'
import levelErrors from 'level-errors'
// https://github.com/rollup/rollup/issues/1267#issuecomment-296395734
// const rimraf = (<any>rimrafProxy).default || rimrafProxy
// const encoding = (<any>encodingProxy).default || encodingProxy
// // const leveldown = (<any>leveldownProxy).default || leveldownProxy
// const levelup = (<any>levelupProxy).default || levelupProxy
import type {
AsyncMapLike,
} from 'async-map-like'
import {
log,
VERSION,
} from './config.js'
export interface IteratorOptions {
gt? : any,
gte? : any,
lt? : any,
lte? : any,
reverse? : boolean,
limit? : number,
prefix? : any,
}
export class FlashStore<K = any, V = any> implements AsyncMapLike<K, V> {
static VERSION = VERSION
private levelDb: level.LevelDB<K, V>
/**
* FlashStore is a Key-Value database tool and makes using leveldb more easy for Node.js
*
* Creates an instance of FlashStore.
* @param {string} [workdir=path.join(appRoot, 'flash-store.workdir')]
* @example
* import { FlashStore } from 'flash-store'
* const flashStore = new FlashStore('flashstore.workdir')
*/
constructor (
public workdir: string,
) {
log.verbose('FlashStore', 'constructor(%s)', workdir)
/**
* `valueEncoding` is a `encoding-down` options.
* See: https://github.com/Level/encoding-down#db--requireencoding-downdb-options
*/
const levelDb = level(workdir, {
valueEncoding: 'json',
})
levelDb.setMaxListeners(17) // default is Infinity
this.levelDb = levelDb
}
public version (): string {
return VERSION
}
/**
* Set data in database
*
* @param {K} key
* @param {V} value
* @returns {Promise<void>}
* @example
* await flashStore.put(1, 1)
*/
public async set (key: K, value: V): Promise<AsyncMapLike<K, V>> {
log.verbose('FlashStore', 'set(%s, %s)', key, typeof value)
log.silly('FlashStore', 'set(%s, %s)', key, JSON.stringify(value))
await this.levelDb.put(key, value)
return this
}
/**
* Get value from database by key
*
* @param {K} key
* @returns {(Promise<V | null>)}
* @example
* console.log(await flashStore.get(1))
*/
public async get (key: K): Promise<V | undefined> {
log.verbose('FlashStore', 'get(%s)', key)
try {
const val = await this.levelDb.get(key)
/**
* We must `await` inside to
* catch the `NotFoundError`
*/
return val
} catch (e) {
if (e instanceof levelErrors.NotFoundError) {
return undefined
}
throw e
}
}
/**
* Del data by key
*
* @param {K} key
* @returns {Promise<void>}
* @example
* await flashStore.del(1)
*/
// public async del (key: K): Promise<void> {
// log.verbose('FlashStore', '`del()` DEPRECATED. use `delete()` instead')
// await this.delete(key)
// }
public async delete (key: K): Promise<boolean> {
log.verbose('FlashStore', 'delete(%s)', key)
await this.levelDb.del(key)
// TODO: `del` returns `true` or `false`
return true
}
/**
* @typedef IteratorOptions
*
* @property { any } gt - Matches values that are greater than a specified value
* @property { any } gte - Matches values that are greater than or equal to a specified value.
* @property { any } lt - Matches values that are less than a specified value.
* @property { any } lte - Matches values that are less than or equal to a specified value.
* @property { boolean } reverse - Reverse the result set
* @property { number } limit - Limits the number in the result set.
* @property { any } prefix - Make the same prefix key get together.
*/
/**
* Find keys by IteratorOptions
*
* @param {IteratorOptions} [options={}]
* @returns {AsyncIterableIterator<K>}
* @example
* const flashStore = new FlashStore('flashstore.workdir')
* for await(const key of flashStore.keys({gte: 1})) {
* console.log(key)
* }
*/
public async * keys (options: IteratorOptions = {}): AsyncIterableIterator<K> {
log.verbose('FlashStore', 'keys()')
// options = Object.assign(options, {
// keys : true,
// values : false,
// })
if (options.prefix) {
if (options.gte || options.lte) {
throw new Error('can not specify `prefix` with `gte`/`lte` together.')
}
options.gte = options.prefix
options.lte = options.prefix + '\xff'
}
for await (const [key] of this.entries(options)) {
yield key
}
}
/**
* Find all values
*
* @returns {AsyncIterableIterator<V>}
* @example
* const flashStore = new FlashStore('flashstore.workdir')
* for await(const value of flashStore.values()) {
* console.log(value)
* }
*/
public async * values (options: IteratorOptions = {}): AsyncIterableIterator<V> {
log.verbose('FlashStore', 'values()')
// options = Object.assign(options, {
// keys : false,
// values : true,
// })
for await (const [, value] of this.entries(options)) {
yield value
}
}
/**
* Get the size of the database
* @returns {Promise<number>}
* @example
* const size = await flashStore.size
* console.log(`database size: ${size}`)
*/
// * @deprecated use property `size` instead
// public async count (): Promise<number> {
// log.warn('FlashStore', '`count()` DEPRECATED. use `size()` instead.')
// const size = await this.size
// return size
// }
public get size (): Promise<number> {
log.verbose('FlashStore', 'size()')
/* eslint no-async-promise-executor: 0 */
// TODO: is there a better way to count all items from the db?
return new Promise<number>(async (resolve, reject) => {
try {
let count = 0
for await (const _ of this) {
count++
}
resolve(count)
} catch (e) {
reject(e)
}
})
}
/**
* FIXME: use better way to do this
*/
public async has (key: K): Promise<boolean> {
const val = await this.get(key)
return !!val
}
/**
* TODO: use better way to do this with leveldb
*/
public async clear (): Promise<void> {
for await (const key of this.keys()) {
await this.delete(key)
}
}
get [Symbol.toStringTag] () {
return Promise.resolve('FlashStore')
}
[Symbol.iterator] (): AsyncIterableIterator<[K, V]> {
log.verbose('FlashStore', '[Symbol.iterator]()')
/**
* Huan(202108): what is this???
* does it equals to `entries()`?
*/
return this.entries()
}
/**
* @private
*/
public async * entries (options?: IteratorOptions): AsyncIterableIterator<[K, V]> {
log.verbose('FlashStore', '*entries(%s)', JSON.stringify(options))
const iterator = (this.levelDb as any).db.iterator(options)
while (true) {
const pair = await new Promise<[K, V] | null>((resolve, reject) => {
iterator.next(function (err: any, key: K, val: V) {
if (err) {
reject(err)
}
if (!key && !val) {
return resolve(null)
}
// if (val) {
// val = JSON.parse(val as any)
// }
return resolve([key, val])
})
})
if (!pair) {
break
}
yield pair
}
}
public async * [Symbol.asyncIterator] (): AsyncIterableIterator<[K, V]> {
log.verbose('FlashStore', '*[Symbol.asyncIterator]()')
yield * this.entries()
}
/**
* @private
*/
// public async * streamAsyncIterator (): AsyncIterator<[K, V]> {
// log.warn('FlashStore', 'DEPRECATED *[Symbol.asyncIterator]()')
// const readStream = this.levelDb.createReadStream()
// const endPromise = new Promise<false>((resolve, reject) => {
// readStream
// .once('end', () => resolve(false))
// .once('error', reject)
// })
// let pair: [K, V] | false
// do {
// const dataPromise = new Promise<[K, V]>(resolve => {
// readStream.once('data', (data: any) => resolve([data.key, data.value]))
// })
// pair = await Promise.race([
// dataPromise,
// endPromise,
// ])
// if (pair) {
// yield pair
// }
// } while (pair)
// }
async forEach (
callbackfn: (
value: V,
key: K,
// map: TestAsyncMapLike,
// FIXME(huan) 202007: we have to use any at here, because the typing system is very hard to
// rename `Map` to `TestAsyncMapLike` in this method function parameters.
map: any,
) => void,
thisArg?: any,
): Promise<void> {
log.verbose('FlashStore', 'forEach()')
for await (const [key, value] of this) {
callbackfn.call(thisArg, value, key, this)
}
}
public async close (): Promise<void> {
log.verbose('FlashStore', 'close()')
await this.levelDb.close()
}
/**
* Destroy the database
*
* @returns {Promise<void>}
*/
public async destroy (): Promise<void> {
log.verbose('FlashStore', 'destroy()')
await this.levelDb.close()
await new Promise(resolve => rimraf(this.workdir, resolve))
}
}
export default FlashStore