Skip to content

Commit

Permalink
Include "modulePathResolver" in resolvers module
Browse files Browse the repository at this point in the history
  • Loading branch information
mdwheele committed Jun 2, 2020
1 parent 7d50628 commit c5f24b5
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 13 deletions.
15 changes: 2 additions & 13 deletions examples/5-custom-operation-resolver/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const logger = require('morgan');
const http = require('http');
const { OpenApiValidator } = require('express-openapi-validator');
const { OpenApiValidator, resolvers } = require('express-openapi-validator');

const port = 3000;
const app = express();
Expand All @@ -30,18 +30,7 @@ new OpenApiValidator({
basePath: path.join(__dirname, 'routes'),
// 4. Provide a function responsible for resolving an Express RequestHandler
// function from the current OpenAPI Route object.
resolver: function (basePath, route) {
[controller, method] = route.schema['operationId'].split('.')

const modulePath = path.join(basePath, controller);
const handler = require(modulePath)

if (handler[method] === undefined) {
throw new Error(`Couldn't find a [${method}] function in ${modulePath} when trying to route [${route.method} ${route.expressRoute}].`)
}

return handler[method]
}
resolver: resolvers.modulePathResolver
}
})
.install(app)
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export {
Forbidden,
} from './framework/types';

export * as resolvers from './resolvers'

export class OpenApiValidator {
private readonly options: OpenApiValidatorOpts;

Expand Down
15 changes: 15 additions & 0 deletions src/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,19 @@ export function defaultResolver(handlersPath: string, route: RouteMetadata): Req
}
return tmpModules[modulePath][oId];
}
}

export function modulePathResolver(handlersPath: string, route: RouteMetadata): RequestHandler {
const [controller, method] = route.schema['operationId'].split('.')

const modulePath = path.join(handlersPath, controller);
const handler = require(modulePath)

if (handler[method] === undefined) {
throw new Error(
`Could not find a [${method}] function in ${modulePath} when trying to route [${route.method} ${route.expressRoute}].`
)
}

return handler[method]
}

0 comments on commit c5f24b5

Please sign in to comment.