expresso / validator

JSON Schema validation middleware for Expresso

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Expresso Validator

JSON Schema validation middleware for Expresso

Summary

What is this

This middleware validates an input against a JSON Schema and automatically throws a boom error for badData (which is HTTP code 422 - Unprocessable Entity) if this input is not matched.

Basic Usage

Install:

$ npm i @expresso/validator

Import and use:

import { validate } from '@expresso/validator'

// Your expresso initialization here

const schema = {
  type: 'object',
  properties: {
    name: {
      type: 'string'
    },
    age: {
      type: 'integer'
    }
  },
  additionalProperties: false,
  required: ['name', 'age']
}

app.post('/users', validate(schema), (req: Reques, res: Response, next: NextFunction) => { // ... // })

Validating queries

By default, the validator will match the schema against the body of the request, this is why the root type is { type: 'object' }. It is also possible to validate the query string params:

import { validate } from '@expresso/validator'

// Your expresso initialization here

const schema = {
  type: 'object',
  properties: {
    name: {
      type: 'string'
    },
    age: {
      type: 'integer'
    }
  },
  required: ['name', 'age']
}

app.get('/users', validate.query(schema), (req: Reques, res: Response, next: NextFunction) => { // ... // })

This will validate the whole query string against the given schema.

validateType function

validateType is actually a dummy function that should be removed in runtime. It exists to give type safety for using @expresso/ts-transformer-type-validator

Errors

This validator follows Expresso's directives and returns a Boom error for BadData, right now it is not possible to change this behavior

About

JSON Schema validation middleware for Expresso

License:MIT License


Languages

Language:TypeScript 100.0%