@akala/core
Version:
76 lines • 2.35 kB
JavaScript
import { isPromiseLike } from "../teardown-manager.js";
export const NotHandled = Promise.resolve(undefined);
export function toMiddleware(fn) {
return function (...args) {
let result;
try {
result = fn.apply(this, args);
}
catch (e) {
return e;
}
if (isPromiseLike(result))
return result.then(x => { throw x; }, x => x);
else
throw result;
};
}
export function convertToMiddleware(fn) {
return {
handle: toMiddleware(fn)
};
}
export function convertToErrorMiddleware(fn) {
return {
handleError: toMiddleware(fn)
};
}
/**
* Checks if a value represents a middleware error.
* @template TSpecialNextParam - The special next parameter type.
* @param x - The value to check.
* @returns True if the value is a middleware error, false otherwise.
*/
export function isMiddlewareError(x) {
return typeof x['error'] != 'undefined';
}
/**
* Checks if a middleware is an error middleware.
* @template T - The context argument types.
* @template TSpecialNextParam - The special next parameter type.
* @param middleware - The middleware to check.
* @returns True if the middleware handles errors, false otherwise.
*/
export function isErrorMiddleware(middleware) {
return typeof middleware?.['handleError'] == 'function';
}
/**
* Checks if a middleware is a standard (non-error) middleware.
* @template T - The context argument types.
* @template TSpecialNextParam - The special next parameter type.
* @param middleware - The middleware to check.
* @returns True if the middleware is standard, false otherwise.
*/
export function isStandardMiddleware(middleware) {
return typeof middleware?.['handle'] == 'function';
}
/**
* Processes a middleware with the provided context.
* @template X - The expected result type.
* @template T - The context parameters.
* @template TSpecialNextParam - The special next parameter type.
* @param middleware - The middleware to process.
* @param ...req - The context parameters for processing.
* @returns The processed result.
*/
export function process(middleware, ...req) {
let error;
try {
error = middleware.handle(...req);
}
catch (result) {
return result;
}
throw error;
}
//# sourceMappingURL=shared.js.map