git ssb

0+

wanderer🌟 / js-dfinity-radix-tree



Tree: 523fd9bda6df579abb596ed6e04a5c19c32ef4c2

Files: 523fd9bda6df579abb596ed6e04a5c19c32ef4c2 / remoteDatastore.js

1422 bytesRaw
1const Buffer = require('safe-buffer').Buffer
2const TreeDAG = require('./datastore.js')
3const fetch = require('node-fetch')
4
5module.exports = class RemoteTreeDAG extends TreeDAG {
6 /**
7 * @param dag {object} a level db instance
8 * @param remoteOpts
9 * @param remoteOpts.uri {string} the HTTP uri which has an interface: GET /:key -> value
10 * @param remoteOpts.encoding {string} the encoding of the reponse
11 * @param opts.decoder {object} a cbor decoder
12 */
13 constructor (dag, remoteOpts, decoder) {
14 super(dag, decoder)
15 this.remoteOpts = Object.assign({
16 uri: null,
17 encoding: 'base64'
18 }, remoteOpts)
19 }
20
21 async get (link) {
22 try {
23 return await super.get(link)
24 } catch (e) {
25 if (this.remoteOpts.uri) {
26 await this.fetchRemote(link)
27 return super.get(link)
28 }
29 }
30 }
31
32 fetchRemote (key) {
33 if (!Buffer.isBuffer(key)) {
34 key = Buffer.from(key.buffer)
35 }
36
37 const route = `${this.remoteOpts.uri}/${key.toString('hex')}`
38 return fetch(route)
39 .then(res => res.text())
40 .then(text => {
41 const encoded = Buffer.from(text, this.remoteOpts.encoding)
42 return new Promise((resolve, reject) => {
43 this._dag.put(key, encoded.toString('hex'), () => {
44 resolve(key)
45 })
46 })
47 })
48 .catch(err => {
49 console.warn(`error fetching ${route}:`, err.message)
50 })
51 }
52}
53

Built with git-ssb-web