Skip to content

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

License

Notifications You must be signed in to change notification settings

brandon93s/micro-superstruct

Repository files navigation

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

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published