All files index.js

100% Statements 45/45
100% Branches 19/19
100% Functions 9/9
100% Lines 45/45
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 851x 1x 1x   1x   1x 1x       1x       3x       2x 2x     2x 2x 2x 1x 1x     2x         4x 4x 4x 4x 3x 3x 1x 2x 1x   1x     1x 1x     3x       2x 2x 2x 2x       2x 2x 2x 2x 2x 1x 1x       2x 2x 2x   2x       1x      
const deepcopy = require('deepcopy')
const OPTS = Symbol('options')
const CID = require('cids')
 
module.exports = class Graph {
  constructor (ipfsDag, opts = {format: 'dag-cbor', hashAlg: 'sha2-256'}) {
    this._dag = ipfsDag
    this._opts = opts
  }
 
  setOptions (obj, opts) {
    obj[OPTS] = opts
  }
 
  getOptions (obj) {
    return obj[OPTS] || this._opts
  }
 
  async set (root, path, value) {
    path = path.split('/')
    value = {
      '/': value
    }
    const last = path.pop()
    let {value: foundVal, remainderPath: remainder} = await this._get(root, path)
    if (remainder) {
      for (const elem of remainder) {
        foundVal = foundVal[elem] = {}
      }
    }
    foundVal[last] = value
  }
 
  async _get (root, path) {
    let edge
    while (path.length) {
      const name = path.shift()
      edge = root[name]
      if (edge && typeof edge !== 'string') {
        const link = edge['/']
        if (typeof link === 'string' || Buffer.isBuffer(link)) {
          root = edge['/'] = (await this._dag.get(new CID(link))).value
        } else if (link) {
          root = link
        } else {
          root = edge
        }
      } else {
        path.unshift(name)
        return {value: root, remainderPath: path}
      }
    }
    return {value: root}
  }
 
  async get (root, path) {
    path = path.split('/')
    const last = path.pop()
    const {value} = await this._get(root, path)
    return value[last]
  }
 
  async flush (root, opts) {
    const awaiting = []
    for (const name in root) {
      const edge = root[name]
      const link = edge['/']
      if (typeof link === 'object') {
        awaiting.push(this.flush(link).then(cid => {
          edge['/'] = cid.toBaseEncodedString()
        }))
      }
    }
    await Promise.all(awaiting)
    opts = opts || this.getOptions(root)
    delete root[OPTS]
 
    return this._dag.put(root, opts)
  }
 
  clone (root) {
    return deepcopy(root)
  }
}