Skip to content

Commit

Permalink
Support async operation handler resolver (#921)
Browse files Browse the repository at this point in the history
- Let users define operationHandlers.resolver as a synchronous or
  asynchronous function that returns a request handler
- Make installOperationHandlers and asynchronous function that awaits a
  resolver promise (automatically wraps resolver with promise if needed)
- Update operation handlers middleware to handle an async
  installOperationHandlers.
  • Loading branch information
mdmower-csnw authored Jun 2, 2024
1 parent 4e8bc84 commit a4a7175
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
11 changes: 8 additions & 3 deletions src/framework/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as ajv from 'ajv';
import * as multer from 'multer';
import { FormatsPluginOptions, FormatOptions } from 'ajv-formats';
import { Request, Response, NextFunction } from 'express';
import { FormatsPluginOptions } from 'ajv-formats';
import { Request, Response, NextFunction, RequestHandler } from 'express';
import { RouteMetadata } from './openapi.spec.loader';
export { OpenAPIFrameworkArgs };

export type BodySchema =
Expand Down Expand Up @@ -63,7 +64,11 @@ export type ValidateSecurityOpts = {

export type OperationHandlerOptions = {
basePath: string;
resolver: Function;
resolver: (
handlersPath: string,
route: RouteMetadata,
apiDoc: OpenAPIV3.Document,
) => RequestHandler | Promise<RequestHandler>;
};

export type Format = {
Expand Down
15 changes: 5 additions & 10 deletions src/openapi.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,11 +221,8 @@ export class OpenApiValidator {
middlewares.push(function operationHandlersMiddleware(req, res, next) {
if (router) return router(req, res, next);
return pContext
.then(
({ context }) =>
(router = self.installOperationHandlers(req.baseUrl, context)),
)
.then((router) => router(req, res, next))
.then(({context}) => self.installOperationHandlers(req.baseUrl, context))
.then((installedRouter) => (router = installedRouter)(req, res, next))
.catch(next);
});
}
Expand Down Expand Up @@ -304,7 +301,7 @@ export class OpenApiValidator {
).validate();
}

installOperationHandlers(baseUrl: string, context: OpenApiContext): Router {
async installOperationHandlers(baseUrl: string, context: OpenApiContext): Promise<Router> {
const router = express.Router({ mergeParams: true });

this.installPathParams(router, context);
Expand All @@ -324,10 +321,8 @@ export class OpenApiValidator {
expressRoute.indexOf(baseUrl) === 0
? expressRoute.substring(baseUrl.length)
: expressRoute;
router[method.toLowerCase()](
path,
resolver(basePath, route, context.apiDoc),
);
const handler = await resolver(basePath, route, context.apiDoc);
router[method.toLowerCase()](path, handler);
}
}
return router;
Expand Down

0 comments on commit a4a7175

Please sign in to comment.