Skip to content

Commit

Permalink
Expose keywords option during the initialization(in init method). (#47)
Browse files Browse the repository at this point in the history
Expose keywords option during the initialization(in init method).
Resolve #45
  • Loading branch information
hehoo authored and idanto committed Mar 5, 2019
1 parent a56371c commit 109b2a5
Show file tree
Hide file tree
Showing 12 changed files with 271 additions and 14 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ The function return Promise.
Options currently supports:
- `framework` - Defines in which framework the middleware is working ('koa' or 'express'). As default, set to 'express'.
- `formats` - Array of formats that can be added to `ajv` configuration, each element in the array should include `name` and `pattern`.
- `keywords` - Array of keywords that can be added to `ajv` configuration, each element in the array can be either an object or a function.
If the element is an object, it must include `name` and `definition`. If the element is a function, it should accept `ajv` as its first argument and inside the function you need to call `ajv.addKeyword` to add your custom keyword
- `beautifyErrors`- Boolean that indicates if to beautify the errors, in this case it will create a string from the Ajv error.
- Examples:
- `query/limit should be <= 100` - query param
Expand Down
12 changes: 9 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"swagger-parser": "^6.0.2"
},
"devDependencies": {
"ajv-keywords": "^3.4.0",
"body-parser": "^1.18.3",
"chai": "^4.2.0",
"chai-sinon": "^2.8.1",
Expand Down
2 changes: 1 addition & 1 deletion src/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ function buildParametersValidation(parameters, contentTypes, middlewareOptions)
const options = Object.assign({}, defaultAjvOptions, middlewareOptions.ajvConfigParams);
let ajv = new Ajv(options);

ajvUtils.addCustomKeyword(ajv, middlewareOptions.formats);
ajvUtils.addCustomKeyword(ajv, middlewareOptions.formats, middlewareOptions.keywords);

var ajvParametersSchema = {
title: 'HTTP parameters',
Expand Down
2 changes: 1 addition & 1 deletion src/swagger2/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ function buildBodyValidation(schema, swaggerDefinitions, originalSwagger, curren
const options = Object.assign({}, defaultAjvOptions, middlewareOptions.ajvConfigBody);
let ajv = new Ajv(options);

ajvUtils.addCustomKeyword(ajv, middlewareOptions.formats);
ajvUtils.addCustomKeyword(ajv, middlewareOptions.formats, middlewareOptions.keywords);

if (schema.discriminator) {
return buildInheritance(schema.discriminator, swaggerDefinitions, originalSwagger, currentPath, currentMethod, parsedPath, ajv);
Expand Down
2 changes: 1 addition & 1 deletion src/swagger3/open-api3.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function buildBodyValidation(dereferenced, originalSwagger, currentPath, current
const options = Object.assign({}, defaultAjvOptions, middlewareOptions.ajvConfigBody);
let ajv = new Ajv(options);

ajvUtils.addCustomKeyword(ajv, middlewareOptions.formats);
ajvUtils.addCustomKeyword(ajv, middlewareOptions.formats, middlewareOptions.keywords);

if (bodySchemaV3.discriminator) {
return buildV3Inheritance(dereferenced, originalSwagger, currentPath, currentMethod, ajv);
Expand Down
28 changes: 22 additions & 6 deletions src/utils/ajv-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,33 @@
const filesKeyword = require('../customKeywords/files'),
contentKeyword = require('../customKeywords/contentTypeValidation');

module.exports = {
addCustomKeyword
};

function addCustomKeyword(ajv, formats) {
function addCustomKeyword(ajv, formats, keywords) {
if (formats) {
formats.forEach(function (format) {
ajv.addFormat(format.name, format.pattern);
});
}

if (keywords) {
keywords.forEach((keyword) => {
if (typeof keyword === 'function') {
return keyword(ajv);
}

if (typeof keyword === 'object') {
const name = keyword.name;
const definition = keyword.definition;
if (name && definition) {
return ajv.addKeyword(name, definition);
}
}
});
}

ajv.addKeyword('files', filesKeyword);
ajv.addKeyword('content', contentKeyword);
}
}

module.exports = {
addCustomKeyword
};
34 changes: 34 additions & 0 deletions test/custom-keywords-swagger.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
swagger: "2.0"
info:
version: 1.0.0
title: Swagger with custom ajv keywords
schemes:
- http
consumes:
- application/json
produces:
- application/json
paths:
/keywords:
post:
description: test custom keywords
produces:
- application/json
parameters:
- name: post data
in: body
required: true
description: body data
schema:
type: object
properties:
age:
type: number
range: [15, 30]
prohibited: ['ages']
required:
- age

responses:
'200':
description: Import result
45 changes: 44 additions & 1 deletion test/express/middleware-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

var chai = require('chai'),
expect = chai.expect,
sinon = require('sinon'),
chaiSinon = require('chai-sinon'),
request = require('supertest');
chai.use(chaiSinon);
Expand Down Expand Up @@ -2306,4 +2305,48 @@ describe('input-validation middleware tests - Express', function () {
});
});
});
describe('Keywords', function () {
var app;
before(function () {
return require('./test-server-keywords').then(function (testServer) {
app = testServer;
});
});
it('should pass the validation by the range keyword', function (done) {
request(app)
.post('/keywords')
.send({ age: 20 })
.expect(200, function (err, res) {
if (err) {
throw err;
}
expect(res.body.result).to.equal('OK');
done();
});
});
it('should be failed by the range keyword', function (done) {
request(app)
.post('/keywords')
.send({ age: 50 })
.expect(400, function (err, res) {
if (err) {
throw err;
}
expect(res.body.more_info).to.includes('body/age should be <= 30');
done();
});
});
it('should be failed by the prohibited keyword', function (done) {
request(app)
.post('/keywords')
.send({ ages: 20, age: 20 })
.expect(400, function (err, res) {
if (err) {
throw err;
}
expect(res.body.more_info).to.includes('body should NOT be valid');
done();
});
});
});
});
48 changes: 48 additions & 0 deletions test/express/test-server-keywords.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var inputValidation = require('../../src/middleware');
var range = require('ajv-keywords/keywords/range');

const definition = {
type: 'object',
macro: function (schema) {
if (schema.length === 0) return true;
if (schema.length === 1) return {not: {required: schema}};
var schemas = schema.map(function (prop) {
return {required: [prop]};
});
return {not: {anyOf: schemas}};
},
metaSchema: {
type: 'array',
items: {
type: 'string'
}
}
};

var inputValidationOptions = {
keywords: [range, { name: 'prohibited', definition }],
beautifyErrors: true,
firstError: true,
expectFormFieldsInBody: true
};

module.exports = inputValidation.init('test/custom-keywords-swagger.yaml', inputValidationOptions)
.then(function () {
var app = express();
app.use(bodyParser.json());
app.post('/keywords', inputValidation.validate, function (req, res, next) {
res.json({ result: 'OK' });
});
app.use(function (err, req, res, next) {
if (err instanceof inputValidation.InputValidationError) {
res.status(400).json({ more_info: err.errors });
}
});

module.exports = app;

return Promise.resolve(app);
});
51 changes: 50 additions & 1 deletion test/koa/middleware-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

var chai = require('chai'),
expect = chai.expect,
sinon = require('sinon'),
chaiSinon = require('chai-sinon'),
request = require('supertest');
chai.use(chaiSinon);
Expand Down Expand Up @@ -2361,4 +2360,54 @@ describe('input-validation middleware tests - Koa', function () {
});
});
});
describe('Keywords', function () {
var app;
before(function () {
return require('./test-server-keywords').then(function (testServer) {
app = testServer;
});
});
beforeEach(function (){
app = app.listen(8888);
});
afterEach(function () {
app.close();
});
it('should pass the validation by the range keyword', function (done) {
request(app)
.post('/keywords')
.send({ age: 20 })
.expect(200, function (err, res) {
if (err) {
throw err;
}
expect(res.body.result).to.equal('OK');
done();
});
});
it('should be failed by the range keyword', function (done) {
request(app)
.post('/keywords')
.send({ age: 50 })
.expect(400, function (err, res) {
if (err) {
throw err;
}
expect(res.body.more_info).to.includes('body/age should be <= 30');
done();
});
});
it('should be failed by the prohibited keyword', function (done) {
request(app)
.post('/keywords')
.send({ ages: 20, age: 20 })
.expect(400, function (err, res) {
if (err) {
throw err;
}
expect(res.body.more_info).to.includes('body should NOT be valid');
done();
});
});
});
});
58 changes: 58 additions & 0 deletions test/koa/test-server-keywords.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
'use strict';

const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const inputValidation = require('../../src/middleware');
var range = require('ajv-keywords/keywords/range');

const definition = {
type: 'object',
macro: function (schema) {
if (schema.length === 0) return true;
if (schema.length === 1) return {not: {required: schema}};
var schemas = schema.map(function (prop) {
return {required: [prop]};
});
return {not: {anyOf: schemas}};
},
metaSchema: {
type: 'array',
items: {
type: 'string'
}
}
};

let app = new Koa();
let router = new Router();

app.use(async function(ctx, next) {
try {
await next();
} catch (err) {
if (err instanceof inputValidation.InputValidationError) {
ctx.status = 400;
ctx.body = { more_info: JSON.stringify(err.errors) };
}
}
});
app.use(bodyParser());
app.use(router.routes());

var inputValidationOptions = {
keywords: [range, { name: 'prohibited', definition }],
beautifyErrors: true,
firstError: true,
expectFormFieldsInBody: true,
framework: 'koa'
};

module.exports = inputValidation.init('test/custom-keywords-swagger.yaml', inputValidationOptions)
.then(function () {
router.post('/keywords', inputValidation.validate, function (ctx, next) {
ctx.status = 200;
ctx.body = { result: 'OK' };
});
return Promise.resolve(app);
});

0 comments on commit 109b2a5

Please sign in to comment.