Skip to content

Commit

Permalink
json schema validator
Browse files Browse the repository at this point in the history
  • Loading branch information
XVincentX committed Mar 16, 2019
1 parent b3323bb commit 1720823
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
33 changes: 33 additions & 0 deletions lib/conditions/json-schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const express = require('express');
const schemas = require('../schemas');
const logger = require('../logger').gateway;

module.exports = {
name: 'json-schema',
schema: {
$id: 'http://express-gateway.io/schemas/policies/json-schema.json',
type: 'object',
properties: {
schema: {
type: 'object',
description: 'Json schema to validate against.',
examples: ['{"type":"string"}']
},
extendedErrors: {
type: 'boolean',
default: false,
description: 'Value istructing the gateway to return the extended Schema Validation errors or a generic Unprocessable Entity'
}
},
required: ['schema', 'extendedErrors']
},
handler: config => {
const validator = schemas.register(String(), String(), config.schema);
return req => {
const { isValid, error } = validator(req.body);
logger.warn(error);
return isValid;
};
},
middlewares: [express.json(), express.urlencoded({ extended: false })]
};
5 changes: 3 additions & 2 deletions lib/conditions/predefined.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const minimatch = require('minimatch');
const jsonSchema = require('./json-schema');

const grabArray = config => {
const { conditions } = require('./index');
Expand Down Expand Up @@ -190,6 +191,6 @@ module.exports = [
schema: {
$id: 'http://express-gateway.io/schemas/conditions/tlsClientAuthenticated.json'
}
}

},
jsonSchema
];
7 changes: 5 additions & 2 deletions lib/gateway/pipelines.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ function configurePipeline(pipelinePoliciesConfig, config) {
policySteps.push({});
}

const middlewares = policySteps.map(policyStep => {
const middlewares = policySteps.flatMap(policyStep => {
const conditionConfig = policyStep.condition;

let condition;
Expand All @@ -138,7 +138,7 @@ function configurePipeline(pipelinePoliciesConfig, config) {
const action = Object.assign({}, policyStep.action, ActionParams.prototype);
const policyMiddleware = policy(action, config);

return (req, res, next) => {
const fn = (req, res, next) => {
if (!conditionConfig || condition(req)) {
log.debug('request matched condition for action', policyStep.action, 'in policy', policyName);
policyMiddleware(req, res, next);
Expand All @@ -147,6 +147,9 @@ function configurePipeline(pipelinePoliciesConfig, config) {
next();
}
};

if (conditionConfig && conditionConfig.middlewares) { return [...middlewares, fn]; }
return fn;
});

router.use(middlewares);
Expand Down

0 comments on commit 1720823

Please sign in to comment.