Skip to content

Commit 9e56910

Browse files
authored
Update example for Koa (#171)
* Added error handler * Removed `module.exports` and `return` * Use 'const' for variable declaration
1 parent 7069b69 commit 9e56910

1 file changed

Lines changed: 18 additions & 4 deletions

File tree

README.md

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -149,11 +149,12 @@ const Koa = require('koa');
149149
const Router = require('koa-router');
150150
const bodyParser = require('koa-bodyparser');
151151
const inputValidation = require('openapi-validator-middleware');
152-
let app = new Koa();
153-
let router = new Router();
152+
const app = new Koa();
153+
const router = new Router();
154154
app.use(bodyParser());
155155
app.use(router.routes());
156-
module.exports = inputValidation.init('test/pet-store-swagger.yaml', { framework: 'koa' });
156+
inputValidation.init('test/pet-store-swagger.yaml', { framework: 'koa' });
157+
157158
router.get('/pets', inputValidation.validate, async (ctx, next) => {
158159
ctx.status = 200;
159160
ctx.body = { result: 'OK' };
@@ -171,7 +172,20 @@ router.put('/pets', inputValidation.validate, async (ctx, next) => {
171172
ctx.body = { result: 'OK' };
172173
});
173174

174-
return app;
175+
app.use(async (ctx, next) => {
176+
try {
177+
return await next();
178+
} catch (err) {
179+
if (err instanceof inputValidation.InputValidationError) {
180+
ctx.status = 400;
181+
ctx.body = err.errors;
182+
}
183+
throw err;
184+
}
185+
})
186+
app.listen(process.env.PORT || 8888, function () {
187+
console.log('listening on', this.address());
188+
});
175189
```
176190

177191
### Fastify

0 commit comments

Comments
 (0)