From 85ca250965143a13e3add31c9e2fba96275b912a Mon Sep 17 00:00:00 2001 From: Marcin Rataj Date: Wed, 31 Jul 2019 16:14:01 +0200 Subject: [PATCH] refactor: promise first addFromURL License: MIT Signed-off-by: Marcin Rataj --- package.json | 1 + .../components/files-regular/add-from-url.js | 36 +++++++------------ 2 files changed, 14 insertions(+), 23 deletions(-) diff --git a/package.json b/package.json index 3cbd44b27b..0064023345 100644 --- a/package.json +++ b/package.json @@ -152,6 +152,7 @@ "peer-id": "~0.12.3", "peer-info": "~0.15.0", "progress": "^2.0.1", + "promise-nodeify": "3.0.1", "promisify-es6": "^1.0.3", "protons": "^1.0.1", "pull-abortable": "^4.1.1", diff --git a/src/core/components/files-regular/add-from-url.js b/src/core/components/files-regular/add-from-url.js index 148250ad22..eb9e5836a6 100644 --- a/src/core/components/files-regular/add-from-url.js +++ b/src/core/components/files-regular/add-from-url.js @@ -2,31 +2,21 @@ const { URL } = require('iso-url') const { default: ky } = require('ky-universal') +const nodeify = require('promise-nodeify') -module.exports = (self) => { - return async (url, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - let files - try { - const res = await ky.get(url) - const path = decodeURIComponent(new URL(res.url).pathname.split('/').pop()) - const content = Buffer.from(await res.arrayBuffer()) - files = await self.add({ content, path }, options) - } catch (err) { - if (callback) { - return callback(err) - } - throw err - } +module.exports = (ipfs) => { + const addFromURL = async (url, opts = {}) => { + const res = await ky.get(url) + const path = decodeURIComponent(new URL(res.url).pathname.split('/').pop()) + const content = Buffer.from(await res.arrayBuffer()) + return ipfs.add({ content, path }, opts) + } - if (callback) { - callback(null, files) + return (name, opts = {}, cb) => { + if (typeof opts === 'function') { + cb = opts + opts = {} } - - return files + return nodeify(addFromURL(name, opts), cb) } }