Skip to content

Commit a4a7175

Browse files
authored
Support async operation handler resolver (#921)
- 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.
1 parent 4e8bc84 commit a4a7175

File tree

2 files changed

+13
-13
lines changed

2 files changed

+13
-13
lines changed

Diff for: src/framework/types.ts

+8-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import * as ajv from 'ajv';
22
import * as multer from 'multer';
3-
import { FormatsPluginOptions, FormatOptions } from 'ajv-formats';
4-
import { Request, Response, NextFunction } from 'express';
3+
import { FormatsPluginOptions } from 'ajv-formats';
4+
import { Request, Response, NextFunction, RequestHandler } from 'express';
5+
import { RouteMetadata } from './openapi.spec.loader';
56
export { OpenAPIFrameworkArgs };
67

78
export type BodySchema =
@@ -63,7 +64,11 @@ export type ValidateSecurityOpts = {
6364

6465
export type OperationHandlerOptions = {
6566
basePath: string;
66-
resolver: Function;
67+
resolver: (
68+
handlersPath: string,
69+
route: RouteMetadata,
70+
apiDoc: OpenAPIV3.Document,
71+
) => RequestHandler | Promise<RequestHandler>;
6772
};
6873

6974
export type Format = {

Diff for: src/openapi.validator.ts

+5-10
Original file line numberDiff line numberDiff line change
@@ -221,11 +221,8 @@ export class OpenApiValidator {
221221
middlewares.push(function operationHandlersMiddleware(req, res, next) {
222222
if (router) return router(req, res, next);
223223
return pContext
224-
.then(
225-
({ context }) =>
226-
(router = self.installOperationHandlers(req.baseUrl, context)),
227-
)
228-
.then((router) => router(req, res, next))
224+
.then(({context}) => self.installOperationHandlers(req.baseUrl, context))
225+
.then((installedRouter) => (router = installedRouter)(req, res, next))
229226
.catch(next);
230227
});
231228
}
@@ -304,7 +301,7 @@ export class OpenApiValidator {
304301
).validate();
305302
}
306303

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

310307
this.installPathParams(router, context);
@@ -324,10 +321,8 @@ export class OpenApiValidator {
324321
expressRoute.indexOf(baseUrl) === 0
325322
? expressRoute.substring(baseUrl.length)
326323
: expressRoute;
327-
router[method.toLowerCase()](
328-
path,
329-
resolver(basePath, route, context.apiDoc),
330-
);
324+
const handler = await resolver(basePath, route, context.apiDoc);
325+
router[method.toLowerCase()](path, handler);
331326
}
332327
}
333328
return router;

0 commit comments

Comments
 (0)