Skip to content

Commit

Permalink
default export in handler #671 (#675)
Browse files Browse the repository at this point in the history
  • Loading branch information
zzgab authored Nov 29, 2021
1 parent 8db56ae commit e68a604
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 7 deletions.
12 changes: 5 additions & 7 deletions src/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,16 @@ export function defaultResolver(
const modulePath = path.join(handlersPath, baseName);
if (!tmpModules[modulePath]) {
tmpModules[modulePath] = require(modulePath);
if (!tmpModules[modulePath][oId]) {
// if oId is not found only module, try the module's default export
tmpModules[modulePath] = tmpModules[modulePath].default;
}
}
if (!tmpModules[modulePath][oId]) {

const handler = tmpModules[modulePath][oId] || tmpModules[modulePath].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 in '${modulePath}'.`,
`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}'.`,
);
}

const handler = tmpModules[modulePath][oId];
cache[cacheKey] = handler;
return handler;
}
Expand Down
46 changes: 46 additions & 0 deletions test/default-export.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import * as express from 'express';
import * as OpenApiValidator from '../src';
import { expect } from 'chai';
import * as request from 'supertest';
import * as path from 'path';

describe('default export resolver', () => {
let server = null;
let app = express();

before(async () => {
app.use(
OpenApiValidator.middleware({
apiSpec: {
openapi: '3.0.0',
info: { version: '1.0.0', title: 'test bug OpenApiValidator' },
paths: {
'/': {
get: {
operationId: 'anything',
// @ts-ignore
'x-eov-operation-handler': 'controller-with-default',
responses: { 200: { description: 'home api' } }
}
},
},
},
operationHandlers: path.join(__dirname, 'resources'),
}),
);

server = app.listen(3000);
console.log('server start port 3000');
});

after(async () => server.close());

it('should use default export operation', async () => {
return request(app)
.get(`/`)
.expect(200)
.then((r) => {
expect(r.body).to.have.property('success').that.equals(true);
});
});
});
3 changes: 3 additions & 0 deletions test/resources/controller-with-default.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function (req, res) {
res.json({success: true}).end();
}

0 comments on commit e68a604

Please sign in to comment.