telefunc
Version:
Remote functions. Instead of API.
42 lines (41 loc) • 1.89 kB
JavaScript
export { executeTelefunction };
import { isAbort, Abort } from '../Abort.js';
import { restoreContext } from '../getContext.js';
import { assertUsage, isPromise } from '../../utils.js';
async function executeTelefunction(runContext) {
const { telefunction, telefunctionArgs } = runContext;
restoreContext(runContext.providedContext);
let telefunctionReturn;
let telefunctionError;
let telefunctionHasErrored = false;
let telefunctionAborted = false;
const onError = (err) => {
assertUsage(typeof err === 'object' && err !== null, `The telefunction ${runContext.telefunctionName}() (${runContext.telefuncFilePath}) threw a non-object error: \`${err}\`. Make sure the telefunction does \`throw new Error(${err})\` instead.`);
assertUsage(err !== Abort, `Missing parentheses \`()\` in \`throw Abort\` (it should be \`throw Abort()\`) at telefunction ${runContext.telefunctionName}() (${runContext.telefuncFilePath}).`);
if (isAbort(err)) {
telefunctionAborted = true;
telefunctionReturn = err.abortValue;
}
else {
telefunctionHasErrored = true;
telefunctionError = err;
}
};
let resultSync;
try {
resultSync = telefunction.apply(null, telefunctionArgs);
}
catch (err) {
onError(err);
}
if (!telefunctionHasErrored && !telefunctionAborted) {
assertUsage(isPromise(resultSync), `The telefunction ${runContext.telefunctionName}() (${runContext.telefuncFilePath}) did not return a promise. A telefunction should always return a promise (e.g. define it as a \`async function\`).`);
try {
telefunctionReturn = await resultSync;
}
catch (err) {
onError(err);
}
}
return { telefunctionReturn, telefunctionAborted, telefunctionHasErrored, telefunctionError };
}