Skip to content

Commit 22b02fa

Browse files
authored
Make init function synchronous (#69)
* Make init synchronous * Fix code from master * Fix readme * Fix package.json * Restore snyk version * Address code review comment
1 parent 98d0f16 commit 22b02fa

30 files changed

Lines changed: 616 additions & 655 deletions

README.md

Lines changed: 40 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,10 @@ This middleware function validates the request body, headers, path parameters an
5555
### express-ajv-swagger-validation.init(pathToSwaggerFile, options)
5656

5757
Initialize the middleware using a swagger definition.
58+
The function executes synchronously and does not return anything.
5859

5960
- `pathToSwaggerFile`: Path to the swagger definition.
6061
- `options`: Additional options for the middleware (see below).
61-
- **Return Value:** Promise
6262

6363
#### Options
6464

@@ -96,28 +96,26 @@ If the element is an object, it must include `name` and `definition`. If the ele
9696
## Usage Example
9797
### Express
9898
```js
99-
swaggerValidator.init('test/unit-tests/input-validation/pet-store-swagger.yaml')
100-
.then(function () {
101-
const app = express();
102-
app.use(bodyParser.json());
103-
app.get('/pets', swaggerValidator.validate, function (req, res, next) {
104-
return res.json({ result: 'OK' });
105-
});
106-
app.post('/pets', swaggerValidator.validate, function (req, res, next) {
107-
return res.json({ result: 'OK' });
108-
});
109-
app.get('/pets/:petId', swaggerValidator.validate, function (req, res, next) {
110-
return res.json({ result: 'OK' });
111-
});
112-
113-
app.use(function (err, req, res) {
114-
if (err instanceof swaggerValidator.InputValidationError) {
115-
return res.status(400).json({ more_info: JSON.stringify(err.errors) });
116-
}
117-
});
118-
119-
const server = app.listen(serverPort, function () {});
120-
});
99+
swaggerValidator.init('test/unit-tests/input-validation/pet-store-swagger.yaml');
100+
const app = express();
101+
app.use(bodyParser.json());
102+
app.get('/pets', swaggerValidator.validate, (req, res, next) => {
103+
return res.json({ result: 'OK' });
104+
});
105+
app.post('/pets', swaggerValidator.validate, (req, res, next) => {
106+
return res.json({ result: 'OK' });
107+
});
108+
app.get('/pets/:petId', swaggerValidator.validate, (req, res, next) => {
109+
return res.json({ result: 'OK' });
110+
});
111+
112+
app.use((err, req, res) => {
113+
if (err instanceof swaggerValidator.InputValidationError) {
114+
return res.status(400).json({ more_info: JSON.stringify(err.errors) });
115+
}
116+
});
117+
118+
const server = app.listen(serverPort, () => {});
121119
```
122120

123121
### Koa
@@ -131,27 +129,25 @@ let app = new Koa();
131129
let router = new Router();
132130
app.use(bodyParser());
133131
app.use(router.routes());
134-
module.exports = inputValidation.init('test/pet-store-swagger.yaml', {framework: 'koa'})
135-
.then(function () {
136-
router.get('/pets', inputValidation.validate, async function(ctx, next) {
137-
ctx.status = 200;
138-
ctx.body = { result: 'OK' };
139-
});
140-
router.post('/pets', inputValidation.validate, async function (ctx, next) {
141-
ctx.status = 200;
142-
ctx.body = { result: 'OK' };
143-
});
144-
router.get('/pets/:petId', inputValidation.validate, async function (ctx, next) {
145-
ctx.status = 200;
146-
ctx.body = { result: 'OK' };
147-
});
148-
router.put('/pets', inputValidation.validate, async function (ctx, next) {
149-
ctx.status = 200;
150-
ctx.body = { result: 'OK' };
151-
});
152-
153-
return Promise.resolve(app);
154-
});
132+
module.exports = inputValidation.init('test/pet-store-swagger.yaml', {framework: 'koa'});
133+
router.get('/pets', inputValidation.validate, async (ctx, next) => {
134+
ctx.status = 200;
135+
ctx.body = { result: 'OK' };
136+
});
137+
router.post('/pets', inputValidation.validate, async (ctx, next) => {
138+
ctx.status = 200;
139+
ctx.body = { result: 'OK' };
140+
});
141+
router.get('/pets/:petId', inputValidation.validate, async (ctx, next) => {
142+
ctx.status = 200;
143+
ctx.body = { result: 'OK' };
144+
});
145+
router.put('/pets', inputValidation.validate, async (ctx, next) => {
146+
ctx.status = 200;
147+
ctx.body = { result: 'OK' };
148+
});
149+
150+
return app;
155151
```
156152

157153
## Important Notes

src/middleware.js

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,7 @@ function init(swaggerPath, options) {
2222

2323
// build schema for requests only
2424
let schemaBuilderOptions = Object.assign({}, options, { buildRequests: true, buildResponses: false });
25-
return apiSchemaBuilder.buildSchema(swaggerPath, schemaBuilderOptions).then((receivedSchemas) => {
26-
schemas = receivedSchemas;
27-
});
25+
schemas = apiSchemaBuilder.buildSchemaSync(swaggerPath, schemaBuilderOptions);
2826
}
2927

3028
function validate(...args) {

test/express/middleware-custom-formatters-test.js

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@ const request = require('supertest');
44
describe('Simple server - custom formatters', () => {
55
let app;
66
before(() => {
7-
return require('./test-simple-server-custom-formatters').then((testServer) => {
8-
app = testServer;
9-
});
7+
app = require('./test-simple-server-custom-formatters')();
108
});
119
it('should use custom formatter for thrown error', (done) => {
1210
request(app)

test/express/middleware-test.js

Lines changed: 24 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,29 @@
11
'use strict';
22

3-
var chai = require('chai'),
3+
const chai = require('chai'),
44
expect = chai.expect,
55
chaiSinon = require('sinon-chai'),
66
request = require('supertest');
77
chai.use(chaiSinon);
88

99
describe('input-validation middleware tests - Express', function () {
1010
describe('init function tests', function () {
11-
it('should reject the promise in case the file doesn\'t exists', function () {
11+
it('should throw an error in case the file doesn\'t exists', function () {
1212
let middleware = require('../../src/middleware');
13-
14-
middleware.init('', {
15-
ajvConfigBody: true,
16-
firstError: 'dsadsa'
17-
});
18-
return middleware.init('test/pet-store-swagger1.yaml')
19-
.catch(function (err) {
20-
expect(err).to.exist;
21-
});
13+
expect(() => {
14+
middleware.init('test/pet-store-swagger1.yaml')
15+
}).to.throw
2216
});
2317
it('should resolve without formats', function () {
2418
let rewire = require('rewire');
2519
let middleware = rewire('../../src/middleware');
26-
return middleware.init('test/pet-store-swagger.yaml');
20+
middleware.init('test/pet-store-swagger.yaml');
2721
});
2822
});
2923
describe('Simple server - no options', function () {
30-
var app;
24+
let app;
3125
before(function () {
32-
return require('./test-simple-server').then(function (testServer) {
33-
app = testServer;
34-
});
26+
app = require('./test-simple-server')();
3527
});
3628
it('valid request - should pass validation', function (done) {
3729
request(app)
@@ -378,11 +370,9 @@ describe('input-validation middleware tests - Express', function () {
378370
});
379371
});
380372
describe('Simple server - type coercion enabled', function () {
381-
var app;
373+
let app;
382374
before(function () {
383-
return require('./test-simple-server-with-coercion').then(function (testServer) {
384-
app = testServer;
385-
});
375+
app = require('./test-simple-server-with-coercion')();
386376
});
387377
it('request with wrong parameter type - should pass validation due to coercion', function (done) {
388378
request(app)
@@ -545,11 +535,9 @@ describe('input-validation middleware tests - Express', function () {
545535
});
546536
});
547537
describe('Simple server - with base path', function () {
548-
var app;
538+
let app;
549539
before(function () {
550-
return require('./test-simple-server-with-base-path').then(function (testServer) {
551-
app = testServer;
552-
});
540+
app = require('./test-simple-server-with-base-path')();
553541
});
554542
it('valid request - should pass validation', function (done) {
555543
request(app)
@@ -939,11 +927,9 @@ describe('input-validation middleware tests - Express', function () {
939927
});
940928
});
941929
describe('Simple server using routes', function () {
942-
var app;
930+
let app;
943931
before(function () {
944-
return require('./test-simple-server-base-route').then(function (testServer) {
945-
app = testServer;
946-
});
932+
app = require('./test-simple-server-base-route')();
947933
});
948934
it('valid request - should pass validation', function (done) {
949935
request(app)
@@ -1290,11 +1276,9 @@ describe('input-validation middleware tests - Express', function () {
12901276
});
12911277
});
12921278
describe('Server with options - beautify and one error', function () {
1293-
var app;
1279+
let app;
12941280
before(function () {
1295-
return require('./test-server-with-options').then(function (testServer) {
1296-
app = testServer;
1297-
});
1281+
app = require('./test-server-with-options')();
12981282
});
12991283
it('valid request - should pass validation', function (done) {
13001284
request(app)
@@ -1685,11 +1669,9 @@ describe('input-validation middleware tests - Express', function () {
16851669
});
16861670
});
16871671
describe('Server with options - Only beautify errors', function () {
1688-
var app;
1672+
let app;
16891673
before(function () {
1690-
return require('./test-server-with-options-more-than-1-error').then(function (testServer) {
1691-
app = testServer;
1692-
});
1674+
app = require('./test-server-with-options-more-than-1-error')();
16931675
});
16941676
it('valid request - should pass validation', function (done) {
16951677
request(app)
@@ -2039,11 +2021,9 @@ describe('input-validation middleware tests - Express', function () {
20392021
});
20402022
});
20412023
describe('Inheritance', function () {
2042-
var app;
2024+
let app;
20432025
before(function () {
2044-
return require('./test-server-inheritance').then(function (testServer) {
2045-
app = testServer;
2046-
});
2026+
app = require('./test-server-inheritance')();
20472027
});
20482028
it('should pass', function (done) {
20492029
request(app)
@@ -2207,11 +2187,9 @@ describe('input-validation middleware tests - Express', function () {
22072187
});
22082188
});
22092189
describe('FormData', function () {
2210-
var app;
2190+
let app;
22112191
before(function () {
2212-
return require('./test-server-formdata').then(function (testServer) {
2213-
app = testServer;
2214-
});
2192+
app = require('./test-server-formdata')();
22152193
});
22162194
it('only required files exists should pass', function (done) {
22172195
request(app)
@@ -2310,11 +2288,9 @@ describe('input-validation middleware tests - Express', function () {
23102288
});
23112289
});
23122290
describe('Keywords', function () {
2313-
var app;
2291+
let app;
23142292
before(function () {
2315-
return require('./test-server-keywords').then(function (testServer) {
2316-
app = testServer;
2317-
});
2293+
app = require('./test-server-keywords')();
23182294
});
23192295
it('should pass the validation by the range keyword', function (done) {
23202296
request(app)
Lines changed: 34 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,49 @@
11
'use strict';
22

3-
var express = require('express');
4-
var bodyParser = require('body-parser');
5-
var inputValidation = require('../../src/middleware');
6-
var multer = require('multer');
7-
var upload = multer();
3+
const express = require('express');
4+
const bodyParser = require('body-parser');
5+
const inputValidation = require('../../src/middleware');
6+
const multer = require('multer');
7+
const upload = multer();
88

9-
var inputValidationOptions = {
9+
const inputValidationOptions = {
1010
formats: [
1111
{ name: 'double', pattern: /\d+(\.\d+)?/ },
1212
{ name: 'int64', pattern: /^\d{1,19}$/ },
1313
{ name: 'int32', pattern: /^\d{1,10}$/ },
14-
{ name: 'file', validate: () => { return true } }
14+
{
15+
name: 'file',
16+
validate: () => {
17+
return true;
18+
}
19+
}
1520
],
1621
beautifyErrors: true,
1722
firstError: true,
1823
expectFormFieldsInBody: true
1924
};
2025

21-
module.exports = inputValidation.init('test/form-data-swagger.yaml', inputValidationOptions)
22-
.then(function () {
23-
var app = express();
24-
app.use(bodyParser.json());
25-
app.post('/pets/import', upload.any(), inputValidation.validate, function (req, res, next) {
26-
res.json({ result: 'OK' });
27-
});
28-
app.post('/kennels/import', upload.any(), inputValidation.validate, function (req, res, next) {
29-
res.json({ result: 'OK' });
30-
});
31-
app.post('/login', upload.any(), inputValidation.validate, function (req, res, next) {
32-
res.json({ result: 'OK' });
33-
});
34-
app.use(function (err, req, res, next) {
35-
if (err instanceof inputValidation.InputValidationError) {
36-
res.status(400).json({ more_info: err.errors });
37-
}
38-
});
39-
40-
module.exports = app;
26+
module.exports = () => {
27+
inputValidation.init('test/form-data-swagger.yaml', inputValidationOptions);
4128

42-
return Promise.resolve(app);
29+
const app = express();
30+
app.use(bodyParser.json());
31+
app.post('/pets/import', upload.any(), inputValidation.validate, function (req, res, next) {
32+
res.json({ result: 'OK' });
33+
});
34+
app.post('/kennels/import', upload.any(), inputValidation.validate, function (req, res, next) {
35+
res.json({ result: 'OK' });
36+
});
37+
app.post('/login', upload.any(), inputValidation.validate, function (req, res, next) {
38+
res.json({ result: 'OK' });
4339
});
40+
app.use(function (err, req, res, next) {
41+
if (err instanceof inputValidation.InputValidationError) {
42+
res.status(400).json({ more_info: err.errors });
43+
}
44+
});
45+
46+
module.exports = app;
47+
48+
return app;
49+
};

0 commit comments

Comments
 (0)