1.0.11 • Published 4 years ago
@sertis/request-validator v1.0.11
request-validator
====
Express middleware for http request validation.
Contents
Installation
npm i @sertis/request-validator
Example
NOTE: Must use validator before your router middleware.
const app = require('express')()
const Validator = require('request-validator')
const apiConfig = require('/path/to/apiConfig')
const validator = new Validator(apiConfig) //apiConfig is optional.
app.post('/', validator.validate(), (req, res) => {
res.send('Hello!')
})
app.listen(8081, () => {
console.log('Start listen on port 8081')
})
Api configuration
configuration | type | description | default |
---|---|---|---|
require | object | configuration for parameters must exists in the request body | {} |
optional | object | configuration for parameters can exists in the request body | {} |
allowNull | boolean | configuration for optional parameters to allow to keep null parameters in the request body | false |
module.exports = {
'METHOD /endpoint': {
allowNull: true,
require: {
parameter: 'type',
},
optional: {
parameter: 'type',
},
},
}
Configuration for object and array (1.0.8 or Higher)
module.exports = {
'METHOD /endpoint': {
require: {
objectA: 'object', //OR
objectB: {
parameter: 'type',
},
arrayA: 'array', //OR
arrayB: ['type'],
},
optional: {
objectA: 'object', //OR
objectB: {
parameter: 'type',
},
arrayA: 'array', //OR
arrayB: ['type'],
},
},
}
Available variable type
NOTE: Extend from Javascript variable type.
- string
- number
- boolean
- object
- array (1.0.1 or Higher)
Configuration example
module.exports = {
'POST /deletenotebook': {
require: {
notebookName: 'string',
},
},
'POST /importNotebook': {
allowNull: true,
optional: {
notebookName: 'string',
cells: [{
title: 'string',
code: 'string',
}],
},
},
'POST /createNotebook': {
require: {
notebookName: 'string',
},
optional: {
noteBookDetail: 'string',
},
},
}
Error response format
Require parameters validation failed error
{ "error": { "code": 400, "status": "BAD_REQUEST", "message": "Require parameters validation failed", "details": [ "Expected \"notebookName\" to be a \"string\", but got a \"undefined\"" ] } }
Optional parameters validation failed error
{ "error": { "code": 400, "status": "BAD_REQUEST", "message": "Optional parameters validation failed", "details": [ "Expected \"notebookName\" to be a \"string\", but got a \"number\"" ] } }