UNPKG

inngest

Version:

Official SDK for Inngest.com. Inngest is the reliability layer for modern applications. Inngest combines durable execution, events, and queues into a zero-infra platform with built-in observability.

94 lines 2.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getHookStack = exports.InngestMiddleware = void 0; const functions_js_1 = require("../helpers/functions.js"); /** * A middleware that can be registered with Inngest to hook into various * lifecycles of the SDK and affect input and output of Inngest functionality. * * See {@link https://innge.st/middleware} * * @example * * ```ts * export const inngest = new Inngest({ * middleware: [ * new InngestMiddleware({ * name: "My Middleware", * init: () => { * // ... * } * }) * ] * }); * ``` * * @public */ class InngestMiddleware { constructor({ name, init }) { this.name = name; this.init = init; } } exports.InngestMiddleware = InngestMiddleware; /** * Given some middleware and an entrypoint, runs the initializer for the given * `key` and returns functions that will pass arguments through a stack of each * given hook in a middleware's lifecycle. * * Lets the middleware initialize before starting. */ const getHookStack = async ( /** * The stack of middleware that will be used to run hooks. */ middleware, /** * The hook type to initialize. */ key, /** * Arguments for the initial hook. */ arg, transforms) => { // Wait for middleware to initialize const mwStack = await middleware; // Step through each middleware and get the hook for the given key const keyFns = mwStack.reduce((acc, mw) => { const fn = mw[key]; if (fn) { return [...acc, fn]; } return acc; }, []); // Run each hook found in sequence and collect the results const hooksRegistered = await keyFns.reduce(async (acc, fn) => { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return [...(await acc), await fn(arg)]; }, Promise.resolve([])); // Prepare the return object - mutating this instead of using reduce as it // results in cleaner code. const ret = {}; // Step through each hook result and create a waterfall joining each key for (const hook of hooksRegistered) { const hookKeys = Object.keys(hook); for (const key of hookKeys) { let fns = [hook[key]]; const existingWaterfall = ret[key]; if (existingWaterfall) { fns = [existingWaterfall, hook[key]]; } const transform = transforms[key]; ret[key] = (0, functions_js_1.waterfall)(fns, transform); } } // Cache each function in the stack to ensure each can only be called once for (const k of Object.keys(ret)) { const key = k; ret[key] = (0, functions_js_1.cacheFn)(ret[key]); } return ret; }; exports.getHookStack = getHookStack; //# sourceMappingURL=InngestMiddleware.js.map