Skip to content
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

Support ESM import of handler module in default resolver #982

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
6 changes: 3 additions & 3 deletions src/framework/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ export type ValidateSecurityOpts = {
};

export type OperationHandlerOptions = {
basePath: string;
basePath: string | URL;
resolver: (
handlersPath: string,
handlersPath: string | URL,
route: RouteMetadata,
apiDoc: OpenAPIV3.Document,
) => unknown;
Expand Down Expand Up @@ -169,7 +169,7 @@ export interface OpenApiValidatorOpts {
$refParser?: {
mode: 'bundle' | 'dereference';
};
operationHandlers?: false | string | OperationHandlerOptions;
operationHandlers?: false | string | URL | OperationHandlerOptions;
validateFormats?: boolean | 'fast' | 'full';
}

Expand Down
3 changes: 2 additions & 1 deletion src/middlewares/openapi.security.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ class AuthValidator {
const authHeader =
req.headers['authorization'] &&
req.headers['authorization'].toLowerCase();

// req.cookies will be `undefined` without `cookie-parser` middleware
const authCookie =
req.cookies?.[scheme.name] || req.signedCookies?.[scheme.name];
Expand All @@ -241,7 +242,7 @@ class AuthValidator {
if (authHeader && !authHeader.includes('bearer')) {
throw Error(`Authorization header with scheme 'Bearer' required`);
}

if (!authHeader && !authCookie) {
if (scheme.in === 'cookie') {
throw Error(`Cookie authentication required`);
Expand Down
2 changes: 1 addition & 1 deletion src/openapi.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export class OpenApiValidator {
if (options.formats == null) options.formats = {};
if (options.useRequestUrl == null) options.useRequestUrl = false;

if (typeof options.operationHandlers === 'string') {
if (typeof options.operationHandlers === 'string' || options.operationHandlers instanceof URL) {
/**
* Internally, we want to convert this to a value typed OperationHandlerOptions.
* In this way, we can treat the value as such when we go to install (rather than
Expand Down
27 changes: 17 additions & 10 deletions src/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import * as path from 'path';
import { RequestHandler } from 'express';
import { RouteMetadata } from './framework/openapi.spec.loader';
import { OpenAPIV3 } from './framework/types';
import { fileURLToPath, pathToFileURL } from 'url';

// Prevent TypeScript from replacing dynamic import with require()
const dynamicImport = new Function('specifier', 'return import(specifier)');

const cache = {};
export function defaultResolver(
handlersPath: string,
export async function defaultResolver(
handlersPath: string | URL,
route: RouteMetadata,
apiDoc: OpenAPIV3.Document,
): RequestHandler {
): Promise<RequestHandler> {
const tmpModules = {};
const { basePath, expressRoute, openApiRoute, method } = route;
const pathKey = openApiRoute.substring(basePath.length);
Expand All @@ -29,14 +33,17 @@ export function defaultResolver(
`found x-eov-operation-handler for route [${method} - ${expressRoute}]. operationId or x-eov-operation-id required.`,
);
}
if (oId && baseName && typeof handlersPath === 'string') {
const modulePath = path.join(handlersPath, baseName);
if (!tmpModules[modulePath]) {
tmpModules[modulePath] = require(modulePath);
}

const handler = tmpModules[modulePath][oId] || tmpModules[modulePath].default[oId] || tmpModules[modulePath].default;
const hasHandlerPath = typeof handlersPath === 'string' || handlersPath instanceof URL;
if (oId && baseName && hasHandlerPath) {
const modulePath = typeof handlersPath === 'string'
? path.join(handlersPath, baseName)
: path.join(fileURLToPath(handlersPath), baseName);
const importedModule = typeof handlersPath === 'string'
? require(modulePath)
: await dynamicImport(pathToFileURL(modulePath).toString());

const handler = importedModule[oId] || importedModule.default?.[oId] || importedModule.default;

if (!handler) {
throw Error(
`Could not find 'x-eov-operation-handler' with id ${oId} in module '${modulePath}'. Make sure operation '${oId}' defined in your API spec exists as a handler function (or module has a default export) in '${modulePath}'.`,
Expand Down
Loading