0.1.3 • Published 5 years ago

micro-ajv v0.1.3

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

micro-ajv

An Ajv (Another JSON Schema Validator) middleware for Micro to validate request body, url, query parameters and etc.

CircleCI

Installation

npm install --save micro-ajv

Usage

By default, it validates request body and replies with 400 status code if validation fails.

const { send } = require('micro')
const microAjvValidation = require('micro-ajv')

const schema = { type: 'string', maxLength: 1024 }
const validate = microAjvValidation(schema)

const handler = (req, res) => send(res, 200, 'Ok')

module.exports = validate(handler)

Middleware Options

It's possible to configure the middleware behavior by passing options object

OptionDescriptionDefault
ajvAjv options{}
targetPath to data for validations (e.g. query.accountId). It validates request body by default"body"
errorModeEnables change middleware behavior strategy when request validation fails. There are three possible modes: reply — respond with an error; throw — throw an exception; inject – call handler with injected validation errors to the req object"reply"
injectKeyEnables pass validation errors to the req object when error mode is inject"microAjvErrors"
createErrorUse this option if you need to change the default error object. As a first argument, it expects Ajv validation errorserrors => micro.createError(400, 'Bad request')

Examples

Validate req.url and handle validation errors inside the handler:

const { send } = require('micro')
const microAjvValidation = require('micro-ajv')

const schema = { type: 'string', maxLength: 1024 }
const options = { target: 'url', errorMode: 'inject', injectKey: 'errors' }
const validate = microAjvValidation(schema, options)

module.exports = validate((req, res) => {
  console.error(req.errors)
  send(res, 414, 'Request url is too long')
})

Validate req.body and reply with a custom error if it fails

const { send } = require('micro')
const microAjvValidation = require('micro-ajv')

const schema = { type: 'string', maxLength: 1024 }
const options = {
  createError: errors =>
    Object.assign(Error(errors.map(error => error.message)), { statusCode: 400 }),
}

const validate = microAjvValidation(schema, options)

const handler = (req, res) => send(res, 200, 'Ok')

module.exports = validate(handler)

Sometime you may need to throw an exception and probably catch it somewhere else in the project instead of replying with an error immediately.

// handler.js
const { send } = require('micro')
const microAjvValidation = require('micro-ajv')

const schema = { type: 'string', maxLength: 1024 }
const options = {
  errorMode: 'throw',
  createError: errors =>
    Object.assign(Error('Payload validation failed'), { type: 'ApiError', statusCode: 400 }),
}
const validate = microAjvValidation(schema, options)

const handler = (req, res) => send(res, 200, 'Ok')

module.exports = validate(handler)
// middleware.js
module.exports.logApiErrors = handler => (req, res) =>
  handler(req, res).catch(err => {
    if (err.type === 'ApiError') {
      console.log(`ApiError: ${err.message}`)
    }
    throw err
  })
// index.js
const { router, post } = require('microrouter')
const { logApiErrors } = require('./middleware')
const handler = require('./handler')

module.exports = logApiErrors(router(post('/foo', handler)))
0.1.3

5 years ago

0.1.2

5 years ago

0.1.0

5 years ago