1 | const fs = require('fs')
|
2 | const path = require('path')
|
3 | const promisify = require('util').promisify
|
4 | const createHasher = require('multihasher')
|
5 |
|
6 | const isDirectory = dir => fs.statSync(dir).isDirectory()
|
7 | const writeFile = promisify(fs.writeFile)
|
8 | const readFile = promisify(fs.readFile)
|
9 |
|
10 | class FSAddressableStorage {
|
11 | constructor (dir, hasher = createHasher('sha256')) {
|
12 | |
13 |
|
14 |
|
15 | if (!isDirectory(dir)) throw new Error('Not a directory.')
|
16 | this.dir = dir
|
17 | this._hasher = hasher
|
18 | }
|
19 | async set (value, ...args) {
|
20 | if (!Buffer.isBuffer(value)) throw new Error('Invalid type.')
|
21 | let hash = await this.hash(value, ...args)
|
22 | await writeFile(path.join(this.dir, hash), value)
|
23 | return hash
|
24 | }
|
25 | async hash (value, ...args) {
|
26 | if (!Buffer.isBuffer(value)) throw new Error('Invalid type.')
|
27 | return this._hasher(value, ...args)
|
28 | }
|
29 |
|
30 | async get (hash) {
|
31 | return readFile(path.join(this.dir, hash))
|
32 | }
|
33 | }
|
34 |
|
35 | module.exports = (...args) => new FSAddressableStorage(...args)
|