Express middlewares that leverages schm to parse and validate request query and body.
$ npm install --save schm-express
const express = require('express')
const bodyParser = require('body-parser')
const { query, body, errorHandler } = require('schm-express')
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
// request GET /?foo
app.get('/', query({ foo: { type: Boolean, required: true } }), (req, res) => {
console.log(req.query) // { foo: true }
})
// request POST / send { foo: 1 }
app.post('/', body({ foo: Boolean }), (req, res) => {
console.log(req.body) // { foo: true }
})
// request GET / (without required ?foo) will respond with status 400 and error descriptor on response body.
app.use(errorHandler())
Returns an express middleware that validates and parses querystring based on a given schema.
params
Object
const express = require('express')
const { query } = require('schm-express')
const app = express()
// request /?foo&bar=1&bar=baz
app.get('/', query({ foo: Boolean, bar: [String] }), (req, res) => {
console.log(req.query) // { foo: true, bar: ['1', 'baz'] }
})
Returns an express middleware that validates and parses request body based on a given schema.
params
Object
const express = require('express')
const bodyParser = require('body-parser')
const { body } = require('schm-express')
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
// send { foo: 1, bar: 'baz' }
app.post('/', body({ foo: Boolean, bar: [String] }), (req, res) => {
console.log(req.body) // { foo: true, bar: ['baz'] }
})
Handles errors from schm-express.
const express = require('express')
const { query } = require('schm-express')
const app = express()
// request / without querystring
app.post('/', query({ foo: { type: Boolean, required: true } }), (req, res) => {
...
})
app.use(errorHandler())
// it will respond with 400 and error descriptor in response body
MIT © Diego Haz