diff --git a/src/index.js b/src/index.js index 508a210..ccfb728 100644 --- a/src/index.js +++ b/src/index.js @@ -2,7 +2,7 @@ class HlsjsIPFSLoader { constructor(config) { - this._abortFlag = [ false ]; + this._abortFlag = new AbortController(); this.ipfs = config.ipfs this.hash = config.ipfsHash if (config.debug === false) { @@ -28,7 +28,7 @@ class HlsjsIPFSLoader { } abort() { - this._abortFlag[0] = true; + this._abortFlag.abort(); } load(context, config, callbacks) { @@ -106,7 +106,7 @@ class HlsjsIPFSLoader { } return; } - this._abortFlag[0] = false; + this._abortFlag = new AbortController(); getFile(this.ipfs, this.hash, filename, options, this.debug, this._abortFlag).then(res => { const data = (context.responseType === 'arraybuffer') ? res : buf2str(res) stats.loaded = stats.total = data.length @@ -120,9 +120,13 @@ async function getFile(ipfs, rootHash, filename, options, debug, abortFlag) { debug(`Fetching hash for '${rootHash}/${filename}'`) const path = `${rootHash}/${filename}` try { - return await cat(path, options, ipfs, debug, abortFlag) - } catch(ex) { - throw new Error(`File not found: ${rootHash}/${filename}`) + return await cat(path, options, ipfs, debug, abortFlag); + } catch(e) { + if (e.name === "AbortError" || "ABORT_ERR") { + throw new Error(`Cancelled reading '${rootHash}/${filename}' from IPFS`); + } + debug(e.message); + throw new Error(`File not found: '${rootHash}/${filename}'`); } } @@ -130,27 +134,20 @@ function buf2str(buf) { return new TextDecoder().decode(buf) } -async function cat (cid, options, ipfs, debug, abortFlag) { - const parts = [] - let length = 0, offset = 0 - - for await (const buf of ipfs.cat(cid, options)) { - parts.push(buf) - length += buf.length - if (abortFlag[0]) { - debug('Cancel reading from ipfs') - break - } +async function cat (cid, options, ipfs, debug, { signal }) { + const parts = []; + let length = 0, offset = 0; + for await (const buf of ipfs.cat(cid, { ...options, signal })) { + parts.push(buf); + length += buf.length; } - - const value = new Uint8Array(length) + const value = new Uint8Array(length); for (const buf of parts) { - value.set(buf, offset) - offset += buf.length + value.set(buf, offset); + offset += buf.length; } - - debug(`Received data for file '${cid}' size: ${value.length} in ${parts.length} blocks`) - return value + debug(`Received data for file '${ cid }' size: ${ value.length } in ${ parts.length } blocks`); + return value; } exports = module.exports = HlsjsIPFSLoader