|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const IsIpfs = require('is-ipfs') |
| 4 | +const promisify = require('promisify-es6') |
| 5 | +const streamToValueWithTransformer = require('../utils/stream-to-value-with-transformer') |
| 6 | +const moduleConfig = require('../utils/module-config') |
| 7 | +const cleanCID = require('../utils/clean-cid') |
| 8 | + |
| 9 | +module.exports = (arg) => { |
| 10 | + const send = moduleConfig(arg) |
| 11 | + |
| 12 | + const refs = promisify((args, opts, callback) => { |
| 13 | + if (typeof (opts) === 'function') { |
| 14 | + callback = opts |
| 15 | + opts = {} |
| 16 | + } |
| 17 | + opts = module.exports.normalizeOpts(opts) |
| 18 | + |
| 19 | + try { |
| 20 | + args = module.exports.checkArgs(args) |
| 21 | + } catch (err) { |
| 22 | + return callback(err) |
| 23 | + } |
| 24 | + |
| 25 | + const transform = (res, cb) => { |
| 26 | + cb(null, res.map(r => ({ ref: r.Ref, err: r.Err }))) |
| 27 | + } |
| 28 | + |
| 29 | + const request = { |
| 30 | + args, |
| 31 | + path: 'refs', |
| 32 | + qs: opts |
| 33 | + } |
| 34 | + send(request, (err, result) => { |
| 35 | + if (err) { |
| 36 | + return callback(err) |
| 37 | + } |
| 38 | + |
| 39 | + streamToValueWithTransformer(result, transform, callback) |
| 40 | + }) |
| 41 | + }) |
| 42 | + |
| 43 | + refs.local = require('./refs-local')(arg) |
| 44 | + refs.localReadableStream = require('./refs-local-readable-stream')(arg) |
| 45 | + refs.localPullStream = require('./refs-local-pull-stream')(arg) |
| 46 | + |
| 47 | + return refs |
| 48 | +} |
| 49 | + |
| 50 | +module.exports.checkArgs = (args) => { |
| 51 | + const isArray = Array.isArray(args) |
| 52 | + args = isArray ? args : [args] |
| 53 | + |
| 54 | + const res = [] |
| 55 | + for (let arg of args) { |
| 56 | + try { |
| 57 | + arg = cleanCID(arg) |
| 58 | + } catch (err) { |
| 59 | + if (!IsIpfs.ipfsPath(arg)) { |
| 60 | + throw err |
| 61 | + } |
| 62 | + } |
| 63 | + res.push(arg) |
| 64 | + } |
| 65 | + |
| 66 | + return isArray ? res : res[0] |
| 67 | +} |
| 68 | + |
| 69 | +module.exports.normalizeOpts = (opts) => { |
| 70 | + opts = opts || {} |
| 71 | + if (typeof opts.maxDepth === 'number') { |
| 72 | + opts['max-depth'] = opts.maxDepth |
| 73 | + } |
| 74 | + return opts |
| 75 | +} |
0 commit comments