forked from ipfs/js-datastore-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnamespace.js
43 lines (40 loc) · 1.27 KB
/
namespace.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
import { Key } from 'interface-datastore'
import { KeyTransformDatastore } from './keytransform.js'
/**
* @typedef {import('interface-datastore').Datastore} Datastore
* @typedef {import('interface-datastore').Query} Query
* @typedef {import('interface-datastore').KeyQuery} KeyQuery
* @typedef {import('interface-datastore').Options} Options
* @typedef {import('interface-datastore').Batch} Batch
* @typedef {import('./types').KeyTransform} KeyTransform
*/
/**
* Wraps a given datastore into a keytransform which
* makes a given prefix transparent.
*
* For example, if the prefix is `new Key(/hello)` a call
* to `store.put(new Key('/world'), mydata)` would store the data under
* `/hello/world`.
*/
export class NamespaceDatastore extends KeyTransformDatastore {
/**
* @param {Datastore} child
* @param {Key} prefix
*/
constructor (child, prefix) {
super(child, {
convert (key) {
return prefix.child(key)
},
invert (key) {
if (prefix.toString() === '/') {
return key
}
if (!prefix.isAncestorOf(key)) {
throw new Error(`Expected prefix: (${prefix.toString()}) in key: ${key.toString()}`)
}
return new Key(key.toString().slice(prefix.toString().length), false)
}
})
}
}