1 | let createHasher = require('multihasher')
|
2 |
|
3 | class InMemoryContentAddressableStorage {
|
4 | constructor (hasher = createHasher('sha256')) {
|
5 | this._store = new Map()
|
6 | this._hasher = hasher
|
7 | }
|
8 |
|
9 | async get (hash, cb) {
|
10 | let buff = this._store.get(hash)
|
11 | if (typeof buff === 'undefined') throw new Error('Not found.')
|
12 | return buff
|
13 | }
|
14 |
|
15 | async hash (value, ...args) {
|
16 | if (!Buffer.isBuffer(value)) throw new Error('Invalid type.')
|
17 | return this._hasher(value, ...args)
|
18 | }
|
19 |
|
20 | async set (value, ...args) {
|
21 | if (!Buffer.isBuffer(value)) throw new Error('Invalid type.')
|
22 | let hash = await this._hasher(value, ...args)
|
23 | this._store.set(hash, value)
|
24 | return hash
|
25 | }
|
26 |
|
27 | async missing (hashes) {
|
28 | let have = new Set(this._store.keys())
|
29 | let diff = new Set(hashes.filter(h => !have.has(h)))
|
30 | return Array.from(diff)
|
31 | }
|
32 | }
|
33 |
|
34 | module.exports = hasher => new InMemoryContentAddressableStorage(hasher)
|