-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathremoteDatastore.js
More file actions
52 lines (48 loc) · 1.39 KB
/
remoteDatastore.js
File metadata and controls
52 lines (48 loc) · 1.39 KB
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
const Buffer = require('safe-buffer').Buffer
const TreeDAG = require('./datastore.js')
const fetch = require('node-fetch')
module.exports = class RemoteTreeDAG extends TreeDAG {
/**
* @param dag {object} a level db instance
* @param remoteOpts
* @param remoteOpts.uri {string} the HTTP uri which has an interface: GET /:key -> value
* @param remoteOpts.encoding {string} the encoding of the reponse
* @param opts.decoder {object} a cbor decoder
*/
constructor (dag, remoteOpts, decoder) {
super(dag, decoder)
this.remoteOpts = Object.assign({
uri: null,
encoding: 'base64'
}, remoteOpts)
}
async get (link) {
try {
return await super.get(link)
} catch (e) {
if (this.remoteOpts.uri) {
await this.fetchRemote(link)
return super.get(link)
}
}
}
fetchRemote (key) {
if (!Buffer.isBuffer(key)) {
key = Buffer.from(key.buffer)
}
const route = `${this.remoteOpts.uri}/${key.toString('hex')}`
return fetch(route)
.then(res => res.text())
.then(text => {
const encoded = Buffer.from(text, this.remoteOpts.encoding)
return new Promise((resolve, reject) => {
this._dag.put(key, encoded.toString('hex'), () => {
resolve(key)
})
})
})
.catch(err => {
console.warn(`error fetching ${route}:`, err.message)
})
}
}