Skip to content

Commit

Permalink
Add the parameter of express req object to custom validate function
Browse files Browse the repository at this point in the history
  • Loading branch information
yunnysunny committed Nov 27, 2018
1 parent de1fdc7 commit 1d0dc48
Show file tree
Hide file tree
Showing 9 changed files with 94 additions and 14 deletions.
4 changes: 4 additions & 0 deletions changelog.md
@@ -1,3 +1,7 @@
# v0.4.0
## Add
1. Add the parameter of express req object to custom validate function.

# v0.3.0
## Add
1. Add the function of custom validate.
Expand Down
5 changes: 3 additions & 2 deletions doc/api.md
Expand Up @@ -15,7 +15,7 @@
## Functions

<dl>
<dt><a href="#CustomValidateFunction">CustomValidateFunction(value)</a> ⇒ <code>*</code></dt>
<dt><a href="#CustomValidateFunction">CustomValidateFunction(value, [req])</a> ⇒ <code>*</code></dt>
<dd></dd>
</dl>

Expand Down Expand Up @@ -107,13 +107,14 @@ Creates an instance of Validator.

<a name="CustomValidateFunction"></a>

## CustomValidateFunction(value) ⇒ <code>\*</code>
## CustomValidateFunction(value, [req]) ⇒ <code>\*</code>
**Kind**: global function
**Returns**: <code>\*</code> - the validate result, when none error, you can return `false` `undefined` `null` or anything can transform to false, when the value is not suitable, you can return a string or an object.

| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | the value you want to validated |
| [req] | <code>http.IncomingMessage</code> | the req object of express |

<a name="ValidateElement"></a>

Expand Down
7 changes: 6 additions & 1 deletion lib/Validator.js
Expand Up @@ -2,6 +2,7 @@
* @function CustomValidateFunction
*
* @param {*} value the value you want to validated
* @param {http.IncomingMessage=} req the req object of express
* @returns {*} the validate result, when none error, you can return `false` `undefined` `null` or anything can transform to false,
* when the value is not suitable, you can return a string or an object.
*/
Expand Down Expand Up @@ -55,6 +56,7 @@ class Validator {
*/
constructor(schema) {
this.schema = schema;
this._req = null;
this.schemaKeys = Object.keys(this.schema);
this.expectedErrorMsg = {};
for (const key of this.schemaKeys) {
Expand All @@ -68,6 +70,9 @@ class Validator {
}
}
}
setReq(req) {
this._req = req;
}
_isEmptyValue(value) {
return typeof(value) === 'undefined' || value === '' || value === null;
}
Expand Down Expand Up @@ -126,7 +131,7 @@ class Validator {

const customValidator = validateElement.custom;
if (customValidator) {
const result = customValidator(value);
const result = customValidator(value,this._req);
if (!result) {
continue;
}
Expand Down
9 changes: 5 additions & 4 deletions lib/filter.js
Expand Up @@ -44,10 +44,11 @@ module.exports = function(option){
if (!validator) {
return next();
}
const params = req.method === 'POST' ?
req.body :
req.query;
const error = validator.doValidate(Object.assign(params));
validator.setReq(req);
// const params = req.method === 'POST' ?
// req.body :
// req.query;
const error = validator.doValidate(Object.assign({},req.query,req.body));
errorResponseCallback(req, res, next, error);;
}
};
5 changes: 3 additions & 2 deletions package.json
@@ -1,14 +1,14 @@
{
"name": "validator-param",
"version": "0.3.0",
"version": "0.4.0",
"description": "A library, which can create validators to validate request parameters easily. ",
"main": "index.js",
"engines": {
"node": ">=6.0"
},
"scripts": {
"test": "nyc mocha --recursive test/mocha",
"coverage":"nyc report --reporter=text-lcov | coveralls",
"coverage": "nyc report --reporter=text-lcov | coveralls",
"bump_path": "npm version patch -m \"upgrade to %s\"",
"doc": "jsdoc2md lib/*.js > doc/api.md"
},
Expand All @@ -34,6 +34,7 @@
"debug": "~2.6.3",
"ejs": "~2.5.6",
"express": "~4.15.2",
"express-session": "^1.15.6",
"jsdoc-to-markdown": "^3.0.0",
"mocha": "^3.5.0",
"morgan": "~1.8.1",
Expand Down
51 changes: 48 additions & 3 deletions test/mocha/middleware_test.js
@@ -1,6 +1,46 @@
const {expect} = require('chai');
const request = require('supertest');
const app = require('../web/app');

function roleTest(role,code,done) {
var cookie = '';
request(app)
.post('/i/login')
.send({role:role})
.expect(200,{code:0})
.end(function(err,res) {
if (err) {
return done(err);
}
var header = res.header;
var setCookieArray = header['set-cookie'];

for (var i=0,len=setCookieArray.length;i<len;i++) {
var value = setCookieArray[i];
var result = value.match(/^validator_session=([a-zA-Z0-9%\.\-_]+);\s/);
if (result && result.length > 1) {
cookie = result[1];
break;
}
}
if (!cookie) {
return done(new Error('find cookie error'));
}
request(app)
.get('/i/data/list')
.set('Cookie','validator_session=' + cookie)
.query({begin_time:'2017-09-10 10:00:00'})
.expect(200)
.end(function(err,res) {
if (err) {
return done(err);
}
expect(res.body).to.have.property('code').and.equal(code);
done();
});
});
}

describe('test for middleware function of request-param',function() {
it('should return error when required parameter is empty',function(done) {
request(app)
Expand Down Expand Up @@ -29,8 +69,7 @@ describe('test for middleware function of request-param',function() {
done();
});
});

it('should return ok when the parameter is all right',function(done) {
it('should return error when not login',function(done) {
request(app)
.get('/i/data/list')
.query({begin_time:'2017-09-10 10:00:00'})
Expand All @@ -39,8 +78,14 @@ describe('test for middleware function of request-param',function() {
if (err) {
return done(err);
}
expect(res.body).to.have.property('code').and.equal(0);
expect(res.body).to.have.property('code').and.equal(4);
done();
});
});
it('should return error when the login user\' role is not 1',function(done) {
roleTest(2,5,done);
});
it('should return ok when the parameter is all right',function(done) {
roleTest(1,0,done);
});
});
7 changes: 7 additions & 0 deletions test/web/app.js
Expand Up @@ -2,6 +2,7 @@ const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');
const session = require('express-session');
const {filter:requestValidator} = require('../../');
const index = require('./routes/index');

Expand All @@ -17,6 +18,12 @@ app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
name: 'validator_session',
secret: 'chyingp', //
saveUninitialized: false, //
resave: false
}));
app.use(requestValidator({
basePath:path.join(__dirname,'./validators'),
urlPrefix:'/i/',
Expand Down
5 changes: 4 additions & 1 deletion test/web/routes/index.js
Expand Up @@ -5,7 +5,10 @@ var router = express.Router();
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});

router.post('/i/login',function(req,res) {
req.session.user = {role:Number(req.body.role)};
res.send({code:0});
});
router.get('/i/data/list', function(req, res) {
res.send({code:0,data:[{a:1,b:2},{a:3,b:4}]});
});
Expand Down
15 changes: 14 additions & 1 deletion test/web/validators/data_list_schema.js
@@ -1,6 +1,19 @@
module.exports = Object.freeze({
begin_time : {
required:[true,{code:1,msg:'The begin_time is empty'}],
type:[Date,{code:2,msg:'the begin_time should be a Date'}]
type:[Date,{code:2,msg:'the begin_time should be a Date'}],
custom:function(value,req) {
const session = req.session;
if (!session) {
return {code:3,msg:'session invalid'}
}
const user = session.user;
if (!user) {
return {code:4,msg:'invalid user'};
}
if (user.role !== 1) {
return {code:5,msg:'you have no right to do this query'};
}
}
}
});

0 comments on commit 1d0dc48

Please sign in to comment.