micro-joi

4.0.0 • Public • Published

Build Status npm

micro-joi

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

It's possible to validate both body and query parameters, or only one of these. To validate both, use body and query key in the schema:

Joi.object({
    body: Joi.object({
        ...
    }),
    query: Joi.object({
        ...
    })
});

To keep api backward compatible, you can write the shape of your request body directly, look at the examples below.

Examples

const { json, send } = require('micro')
const validation = require('micro-joi')
 
const validator = validation(Joi.object({
    foo: Joi.number().required(),
    bar: Joi.number().required()
}))
 
async function handler (req, res) {
  const body = await json(req)
  send(res, 200, body)
}
 
module.exports = validator(handler)

Sending a POST with a wrong body, e.g. { foo: 42, bar: "fortytwo" }, will return an error with a Joi validation message, status code 400.

or with custom message

const { json, send } = require('micro')
const validation = require('micro-joi')
 
const validator = validation(Joi.object({
    foo: Joi.number().required(),
    bar: Joi.number().required()
}), 'hei! send a correct body plz')
 
async function handler (req, res) {
  const body = await json(req)
  send(res, 200, body)
}

It will return an error with your custom message, status code 400.

Readme

Keywords

none

Package Sidebar

Install

npm i micro-joi

Weekly Downloads

0

Version

4.0.0

License

MIT

Unpacked Size

5.12 kB

Total Files

6

Last publish

Collaborators

  • stearm