forked from ethereumjs/ethereumjs-monorepo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
level.js
54 lines (42 loc) · 1.2 KB
/
level.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
const { Level } = require('level')
const { MemoryLevel } = require('memory-level')
const { Trie } = require('../dist')
const ENCODING_OPTS = { keyEncoding: 'view', valueEncoding: 'view' }
class LevelDB {
_leveldb
constructor(leveldb) {
this._leveldb = leveldb ?? new MemoryLevel(ENCODING_OPTS)
}
async get(key) {
let value = null
try {
value = await this._leveldb.get(key, ENCODING_OPTS)
} catch (error) {
// This should be `true` if the error came from LevelDB
// so we can check for `NOT true` to identify any non-404 errors
if (error.notFound !== true) {
throw error
}
}
return value
}
async put(key, val) {
await this._leveldb.put(key, val, ENCODING_OPTS)
}
async del(key) {
await this._leveldb.del(key, ENCODING_OPTS)
}
async batch(opStack) {
await this._leveldb.batch(opStack, ENCODING_OPTS)
}
shallowCopy() {
return new LevelDB(this._leveldb)
}
}
const trie = new Trie({ db: new LevelDB(new Level('MY_TRIE_DB_LOCATION')) })
async function test() {
await trie.put(Buffer.from('test'), Buffer.from('one'))
const value = await trie.get(Buffer.from('test'))
console.log(value.toString()) // 'one'
}
test()