opnet
Version:
The perfect library for building Bitcoin-based applications.
74 lines (73 loc) • 3.02 kB
JavaScript
export function createSequentialWorker() {
let messageCallback = null;
let terminated = false;
return {
postMessage: (msg) => {
if (terminated || !messageCallback)
return;
const { id, op, data } = msg;
const callback = messageCallback;
void (async () => {
try {
let result;
if (op === 'parse') {
const text = data instanceof ArrayBuffer
? new TextDecoder().decode(data)
: data;
result = JSON.parse(text);
}
else if (op === 'stringify') {
result = JSON.stringify(data);
}
else if (op === 'fetch') {
const { url, payload, timeout, headers } = data;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout || 20000);
try {
const resp = await fetch(url, {
method: 'POST',
headers: headers || {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(payload),
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
}
result = JSON.parse(await resp.text());
}
catch (err) {
clearTimeout(timeoutId);
if (err.name === 'AbortError') {
throw new Error(`Request timed out after ${timeout || 20000}ms`, {
cause: err,
});
}
throw err;
}
}
else {
throw new Error(`Unknown operation: ${op}`);
}
if (!terminated)
callback({ id, result });
}
catch (err) {
if (!terminated) {
callback({ id, error: err instanceof Error ? err.message : String(err) });
}
}
})();
},
onMessage: (callback) => {
messageCallback = callback;
},
terminate: () => {
terminated = true;
messageCallback = null;
},
};
}