Skip to content
This repository was archived by the owner on Mar 8, 2024. It is now read-only.

refactor: abortFlag replaced with AbortController and AbortSignal #26

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 21 additions & 24 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -28,7 +28,7 @@ class HlsjsIPFSLoader {
}

abort() {
this._abortFlag[0] = true;
this._abortFlag.abort();
}

load(context, config, callbacks) {
Expand Down Expand Up @@ -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
Expand All @@ -120,37 +120,34 @@ 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}'`);
}
}

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