UNPKG

ipfs-http-client

Version:
87 lines (82 loc) 2.58 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var cid = require('multiformats/cid'); var objectToCamel = require('./lib/object-to-camel.js'); var configure = require('./lib/configure.js'); var multipartRequest = require('ipfs-core-utils/multipart-request'); var toUrlSearchParams = require('./lib/to-url-search-params.js'); var abortSignal = require('./lib/abort-signal.js'); var nativeAbortController = require('native-abort-controller'); const createAddAll = configure.configure(api => { async function* addAll(source, options = {}) { const controller = new nativeAbortController.AbortController(); const signal = abortSignal.abortSignal(controller.signal, options.signal); const {headers, body, total, parts} = await multipartRequest.multipartRequest(source, controller, options.headers); const [progressFn, onUploadProgress] = typeof options.progress === 'function' ? createProgressHandler(total, parts, options.progress) : [ undefined, undefined ]; const res = await api.post('add', { searchParams: toUrlSearchParams.toUrlSearchParams({ 'stream-channels': true, ...options, progress: Boolean(progressFn) }), onUploadProgress, signal, headers, body }); for await (let file of res.ndjson()) { file = objectToCamel.objectToCamel(file); if (file.hash !== undefined) { yield toCoreInterface(file); } else if (progressFn) { progressFn(file.bytes || 0, file.name); } } } return addAll; }); const createProgressHandler = (total, parts, progress) => parts ? [ undefined, createOnUploadProgress(total, parts, progress) ] : [ progress, undefined ]; const createOnUploadProgress = (size, parts, progress) => { let index = 0; const count = parts.length; return ({loaded, total}) => { const position = Math.floor(loaded / total * size); while (index < count) { const {start, end, name} = parts[index]; if (position < end) { progress(position - start, name); break; } else { progress(end - start, name); index += 1; } } }; }; function toCoreInterface({name, hash, size, mode, mtime, mtimeNsecs}) { const output = { path: name, cid: cid.CID.parse(hash), size: parseInt(size) }; if (mode != null) { output.mode = parseInt(mode, 8); } if (mtime != null) { output.mtime = { secs: mtime, nsecs: mtimeNsecs || 0 }; } return output; } exports.createAddAll = createAddAll;