This repository has been archived by the owner on Sep 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmemory.js
75 lines (62 loc) · 1.43 KB
/
memory.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
'use strict'
const Key = require('./key')
const Adapter = require('./adapter')
const Errors = require('./errors')
/**
* @typedef {import('./types').Pair} Pair
* @typedef {import('./types').Datastore} Datastore
* @typedef {import('interface-store').Options} Options
*/
/**
* @class MemoryDatastore
* @implements {Datastore}
*/
class MemoryDatastore extends Adapter {
constructor () {
super()
/** @type {Record<string, Uint8Array>} */
this.data = {}
}
open () {
return Promise.resolve()
}
close () {
return Promise.resolve()
}
/**
* @param {Key} key
* @param {Uint8Array} val
*/
async put (key, val) { // eslint-disable-line require-await
this.data[key.toString()] = val
}
/**
* @param {Key} key
*/
async get (key) {
const exists = await this.has(key)
if (!exists) throw Errors.notFoundError()
return this.data[key.toString()]
}
/**
* @param {Key} key
*/
async has (key) { // eslint-disable-line require-await
return this.data[key.toString()] !== undefined
}
/**
* @param {Key} key
*/
async delete (key) { // eslint-disable-line require-await
delete this.data[key.toString()]
}
async * _all () {
yield * Object.entries(this.data)
.map(([key, value]) => ({ key: new Key(key), value }))
}
async * _allKeys () {
yield * Object.entries(this.data)
.map(([key]) => new Key(key))
}
}
module.exports = MemoryDatastore