Skip to content

Add lifecycle handlers #786

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions src/backend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import * as path from 'path';
import { OpenAPIBackend, Context } from './backend';
import type { Request } from './router';
import { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';

const testsDir = path.join(__dirname, '..', '__tests__');
Expand Down Expand Up @@ -768,4 +769,120 @@ describe('OpenAPIBackend', () => {
expect(mock).toMatchObject(exampleGarfield);
});
});

describe('lifecycle handlers', () => {
const definition = {
openapi: '3.1.0',
info: {
title: 'api',
version: '1.0.0',
},
paths: {
'/pets': {
get: {
operationId: 'getPets',
responses: {
200: { description: 'ok' },
},
},
},
},
security: [
{
basicAuth: [],
},
],
components: {
securitySchemes: {
basicAuth: {
type: 'http',
scheme: 'basic',
},
},
},
} as OpenAPIV3_1.Document;

let api: OpenAPIBackend<OpenAPIV3_1.Document>;
let request: Request;
let resultOrder: string[];

beforeEach(async () => {
api = new OpenAPIBackend({
definition,
});

resultOrder = [];
request = {
method: 'get',
path: '/pets',
headers: {},
};

const addToResultOrder = (name: string) => jest.fn(async () => resultOrder.push(name));

api.register('getPets', addToResultOrder('operationHandler'));
api.register('notFound', addToResultOrder('notFoundHandler'));
api.register('methodNotAllowed', addToResultOrder('methodNotAllowedHandler'));
api.register('unauthorizedHandler', addToResultOrder('unauthorizedHandler'));
api.register('preRoutingHandler', addToResultOrder('preRoutingHandler'));
api.register('postRoutingHandler', addToResultOrder('postRoutingHandler'));
api.register('postSecurityHandler', addToResultOrder('postSecurityHandler'));
api.register('preOperationHandler', addToResultOrder('preOperationHandler'));
api.register('postResponseHandler', addToResultOrder('postResponseHandler'));
api.registerSecurityHandler('basicAuth', () => true);

await api.init();
});

test('should execute handlers in the correct order for a valid request', async () => {
await api.handleRequest(request);

expect(resultOrder).toEqual([
'preRoutingHandler',
'postRoutingHandler',
'postSecurityHandler',
'preOperationHandler',
'operationHandler',
'postResponseHandler',
]);
});

test('should execute handlers in the correct order when route is not found', async () => {
request.path = '/unknown';
await api.handleRequest(request);

expect(resultOrder).toEqual([
'preRoutingHandler',
'postRoutingHandler',
'notFoundHandler',
'postResponseHandler',
]);
});

test('should execute handlers in the correct order when method is not allowed', async () => {
request.method = 'post'; // No POST handler defined in this path
await api.handleRequest(request);

expect(resultOrder).toEqual([
'preRoutingHandler',
'postRoutingHandler',
'methodNotAllowedHandler',
'postResponseHandler',
]);
});

test('should execute handlers in the correct order when unauthorized', async () => {
api.registerSecurityHandler('basicAuth', () => false);

await api.handleRequest(request);

expect(resultOrder).toEqual([
'preRoutingHandler',
'postRoutingHandler',
'postSecurityHandler',
'unauthorizedHandler',
'postResponseHandler',
]);
});
});
});
40 changes: 37 additions & 3 deletions src/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ export class OpenAPIBackend<D extends Document = Document> {
'400',
'validationFail',
'unauthorizedHandler',
'preRoutingHandler',
'postRoutingHandler',
'postSecurityHandler',
'preOperationHandler',
'postResponseHandler',
];

Expand Down Expand Up @@ -310,10 +314,22 @@ export class OpenAPIBackend<D extends Document = Document> {
// parse request
context.request = this.router.parseRequest(req);

// preRoutingHandler
const preRoutingHandler = this.handlers['preRoutingHandler'];
if (preRoutingHandler) {
await preRoutingHandler(context as Context<D>, ...handlerArgs);
}

// match operation (routing)
try {
context.operation = this.router.matchOperation(req, true);
} catch (err) {
// postRoutingHandler on routing failure
const postRoutingHandler = this.handlers['postRoutingHandler'];
if (postRoutingHandler) {
await postRoutingHandler(context as Context<D>, ...handlerArgs);
}

let handler = this.handlers['404'] || this.handlers['notFound'];
if (err instanceof Error && err.message.startsWith('405')) {
// 405 method not allowed
Expand All @@ -330,6 +346,12 @@ export class OpenAPIBackend<D extends Document = Document> {
// parse request again now with matched operation
context.request = this.router.parseRequest(req, context.operation);

// postRoutingHandler on routing success
const postRoutingHandler = this.handlers['postRoutingHandler'];
if (postRoutingHandler) {
await postRoutingHandler(context as Context<D>, ...handlerArgs);
}

// get security requirements for the matched operation
// global requirements are already included in the router
const securityRequirements = context.operation.security || [];
Expand Down Expand Up @@ -398,6 +420,12 @@ export class OpenAPIBackend<D extends Document = Document> {
...securityHandlerResults,
};

// postSecurityHandler
const postSecurityHandler = this.handlers['postSecurityHandler'];
if (postSecurityHandler) {
await postSecurityHandler(context as Context<D>, ...handlerArgs);
}

// call unauthorizedHandler handler if auth fails
if (!authorized && securityRequirements.length > 0) {
const unauthorizedHandler = this.handlers['unauthorizedHandler'];
Expand Down Expand Up @@ -430,9 +458,15 @@ export class OpenAPIBackend<D extends Document = Document> {
}
}

// preOperationHandler – runs just before the operation handler
const preOperationHandler = this.handlers['preOperationHandler'];
if (preOperationHandler) {
await preOperationHandler(context as Context<D>, ...handlerArgs);
}

// get operation handler
const routeHandler = this.handlers[operationId];
if (!routeHandler) {
const operationHandler = this.handlers[operationId];
if (!operationHandler) {
// 501 not implemented
const notImplementedHandler = this.handlers['501'] || this.handlers['notImplemented'];
if (!notImplementedHandler) {
Expand All @@ -442,7 +476,7 @@ export class OpenAPIBackend<D extends Document = Document> {
}

// handle route
return routeHandler(context as Context<D>, ...handlerArgs);
return operationHandler(context as Context<D>, ...handlerArgs);
}).bind(this)();

// post response handler
Expand Down
Loading