schm-express
v0.4.1
Published
Express middlewares using schm
Downloads
184
Readme
schm-express
Express middlewares that leverages schm to parse and validate request query and body.
Install
$ npm install --save schm-express
Usage
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())
API
Table of Contents
query
Returns an express middleware that validates and parses querystring based on a given schema.
Parameters
params
Object
Examples
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'] }
})
body
Returns an express middleware that validates and parses request body based on a given schema.
Parameters
params
Object
Examples
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'] }
})
errorHandler
Handles errors from schm-express.
Examples
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
License
MIT © Diego Haz