A lightweight express middleware to make basic post request body validations
Install
npm install @stephenboyd/post-validator
Explanation
This package allows you do add simple validations to Express endpoints. To do so, just import the package, create your array of required fields, and start the validator.
Usage
const express = require('express')
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// Import post-validator
const apiValidator = require('post-validator')
const validator = apiValidator.apiValidator
// Create the validation you want
const baseValidator = [
{field: 'itemDescription', type: 'string'},
{field: 'itemNumber', type: 'number'}
]
// Add the validator as a middleware
app.post('/', validator(baseValidator), (req, res) => {
return res.send('hello')
})
// After all endpoints have been set up, initialize the validators
app.use(apiValidator.startValidators)
app.listen(3000, () => {
console.log('app started')
})