micro-superstruct

1.1.0 • Public • Published

micro-superstruct Build Status

A Superstruct wrapper for Micro to validate request body and query parameters.

Install

npm install micro-superstruct

Usage

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:

Error

API

validate(config)

Returns a validator function that can be used to validate a Micro handler.

config

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({})
})

Request Properties

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)
}

License

MIT © Brandon Smith

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.1.0
    1
    • latest

Version History

Package Sidebar

Install

npm i micro-superstruct

Weekly Downloads

2

Version

1.1.0

License

MIT

Unpacked Size

4.98 kB

Total Files

4

Last publish

Collaborators

  • brandon93s