Skip to content

Commit

Permalink
feat: support default exports for controllers
Browse files Browse the repository at this point in the history
  • Loading branch information
williams-nova committed May 12, 2023
1 parent 622df71 commit 250d918
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/middleware/native/oas-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,10 @@ export class OASRouter extends OASBase {

if (!path) throw new errors.RoutingError(`Controller ${opControllerName} not found`);

const controller = await import(pathToFileURL(path));
tmp[expressPath] = {
...tmp[expressPath],
[method.toUpperCase()]: (await import(pathToFileURL(path)))[opId]
[method.toUpperCase()]: controller[opId] ?? controller.default?.[opId]
};

if (!tmp[expressPath][method.toUpperCase()])
Expand Down
12 changes: 11 additions & 1 deletion tests/suites/router.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default () => {
assert.equal(res.data, 'Test service for router middleware');
});
});

it('Should route to controller correctly when controller is async and fail if an error is thrown', async () => {
cfg.useAnnotations = false;
cfg.logger.level = 'off';
Expand All @@ -58,6 +58,16 @@ export default () => {
assert.deepStrictEqual(err.response.data, {error: "Error: Error raised in async controller"});
});
});

it('Should route to controller correctly when controller uses default exports', async () => {
cfg.useAnnotations = false;
await init(cfg);

await axios.get('http://localhost:8080/api/v1/oasRouter/defaultexport').then(res => {
assert.equal(res.status, 200);
assert.equal(res.data, 'Test service for router middleware');
});
});
});
});
}
6 changes: 6 additions & 0 deletions tests/testServer/api/3.0.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,12 @@ paths:
x-router-controller: oasRouterTestController
responses:
'500': {$ref: 'subschemas/responses.yaml#/500'}
/api/v1/oasRouter/defaultexport:
get:
operationId: getRequest
x-router-controller: oasRouterDefaultExportTestController
responses:
'500': {$ref: 'subschemas/responses.yaml#/500'}

# OAS RESPONSE VALIDATOR TEST ENDPOINT
/api/v1/oasResponseValidator:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/** @oastools {Controller} /api/v1/oasRouter */
import * as service from './oasRouterTestService.js';


export default {
/**
* @oastools {method} GET
*/
getRequest(req, res, next) {
service.getRequest(req, res, next);
},
}

0 comments on commit 250d918

Please sign in to comment.