A Superstruct wrapper for Micro to validate request body and query parameters.
npm install micro-superstruct
micro-superstruct exports a validate function that allows you to create API validators from any Struct
:
const {object, string, number} = require('superstruct')
const {json, send} = require('micro')
const validate = require('micro-superstruct')
// define a Superstruct `Struct`
const Unicorn = object({
name: string(),
age: number(),
color: string()
})
// create a validator
const validator = validate(Unicorn)
// write your Micro API
const handler = async (req, res) => {
const body = await json(req)
send(res, 200, body)
}
// export validated service
module.exports = validator(handler)
Requests that fail validation will return a 400 error along with a Superstruct validation message:
Returns a validator function that can be used to validate a Micro handler.
Type: Struct | object
Passing a Struct
directly will configure request body validation using the provided validator.
Passing an object
allows for validation of both the request body and query string. Both are optional.
// body validation
validate(object({}))
// body and/or query validation
validate({
body: object({}),
query: object({})
})
micro-superstruct attaches validated body
and/or query
objects to the request object for use by the API handler:
const validator = validate(Unicorn)
const handler = async (req, res) => {
const {body, query} = req
send(res, 200, body)
}
MIT © Brandon Smith