koas-operations
Version:
Koas operations maps operation IDs to Koa controller functions.
66 lines (65 loc) • 2.37 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.operations = void 0;
/**
* Middleware which throws a status code `501 Not Implemented`.
*
* @param ctx - The Koa context.
*/
function notImplemented(ctx) {
ctx.throw(501);
}
/**
* Map OpenAPI operation IDs to controllers.
*
* @param options - The for controlling how operation IDs are handled.
* @returns Koas middleware.
*/
function operations({ controllers = {}, fallback = notImplemented, throwOnExtraneous = true, throwOnNotImplemented = true, } = {}) {
return ({ document }) => {
if (throwOnNotImplemented || throwOnExtraneous) {
const operationObjects = Object.values(document.paths)
.flatMap((path) => [
path.delete,
path.get,
path.head,
path.options,
path.patch,
path.post,
path.put,
path.trace,
])
.filter(Boolean);
if (throwOnNotImplemented) {
for (const { operationId } of operationObjects) {
if (typeof operationId !== 'string') {
throw new TypeError('Detected an operation object without an operationId');
}
if (typeof controllers[operationId] !== 'function') {
throw new TypeError(`Missing controller for operationId: ${operationId}`);
}
}
}
if (throwOnExtraneous) {
for (const id of Object.keys(controllers)) {
if (!operationObjects.some(({ operationId }) => id === operationId)) {
throw new Error(`Found extraneous controller: ${id}`);
}
}
}
}
return (ctx, next) => {
const { operationObject } = ctx.openApi;
const { operationId } = operationObject;
if (typeof operationId !== 'string') {
return fallback(ctx, next);
}
const operation = controllers[operationId];
if (typeof operation !== 'function') {
return fallback(ctx, next);
}
return operation(ctx, next);
};
};
}
exports.operations = operations;