UNPKG

@whook/whook

Version:

Build strong and efficient REST web services.

51 lines 1.88 kB
import { autoService, location, } from 'knifecycle'; import { YError } from 'yerror'; // One can just inject a route handler // but for mocking the use of cloud // functions/lambdas this service can // be useful async function initRouteInvoker({ ROUTES_DEFINITIONS, $injector, log, }) { log('warning', '🖥 - Running with the route invoker service.'); let disposing = false; const currentInvocations = []; const routeInvoker = (async (functionName, parameters, wait = false) => { if (disposing) { throw new YError('E_DISPOSING'); } const responsePromise = (async () => { const routeHandler = (await $injector([functionName]))[functionName]; const response = await routeHandler({ query: {}, headers: {}, path: {}, cookies: {}, body: {}, options: {}, ...parameters, }, ROUTES_DEFINITIONS[functionName].module.definition); return response; })(); if (wait === true) { return await responsePromise; } else { const promise = responsePromise.then(() => { currentInvocations.splice(currentInvocations.indexOf(promise), 1); }); currentInvocations.push(promise); } return undefined; }); return { service: routeInvoker, dispose: async () => { disposing = true; if (currentInvocations.length) { log('warning', `🖥 - Waiting for pending route invocations to end ( ${currentInvocations.length} left).`); await Promise.all(currentInvocations); } }, }; } export default location(autoService(initRouteInvoker), import.meta.url); //# sourceMappingURL=routeInvoker.js.map