0.1.3 • Published 8 months ago

@novice1/validator-typebox v0.1.3

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

@novice1/validator-typebox

Typebox validator to use with @novice1/routing.

It provides a middleware that can validate req.params, req.body, req.query, req.headers, req.cookies and req.files against a schema using @sinclair/typebox.

Installation

npm install @novice1/validator-typebox

Usage

Set validator

// router.ts

import routing from '@novice1/routing'
import { validatorTypebox } from '@novice1/validator-typebox'

export default const router = routing()

router.setValidators(
  validatorTypebox(
    // compile options
    { references: [] },
    // middleware in case validation fails
    function onerror(err, req, res, next) {
      res.status(400).json(err)
    }
    // name of the property containing the schema
    'schema'
  )
)

Create schema

// schema.ts

import { Type, Static } from '@sinclair/typebox'
import { ValidatorTypeboxSchema } from '@novice1/validator-typebox'
import router from './router'

// schema for "req.body"
const bodySchema = Type.Object({                
  name: Type.String()                            
})

// type for "req.body"
export type BodyItem = Static<typeof bodySchema>

export const routeSchema: ValidatorTypeboxSchema = Type.Object({
    body: bodySchema
})

// or
/*
export const routeSchema: ValidatorTypeboxSchema = {
    body: bodySchema
}
*/

// or
/*
export const routeSchema: ValidatorTypeboxSchema = {
    body: {                
        name: Type.String()                            
    }
}
*/

Create route

import routing from '@novice1/routing'
import express from 'express'
import router from './router'
import { BodyItem, routeSchema } from './schema'

router.post(
  {
    name: 'Post item',
    path: '/items',

    parameters: {
        // the schema to validate
        schema: routeSchema
    },

    // body parser
    preValidators: express.json()
  },
  function (req: routing.Request<unknown, { name: string }, BodyItem>, res) {
    res.json({ name: req.body.name })
  }
)

Overrides

Override the validator's options and the error handler for a route.

import routing from '@novice1/routing'
import { ValidatorTypeboxOptions } from '@novice1/validator-typebox'
import router from './router'

const onerror: routing.ErrorRequestHandler = (err, req, res) => {
  res.status(400).json(err)
}

const validatorTypeboxOptions: ValidatorTypeboxOptions = { }

router.get(
  {
    path: '/override',
    parameters: {
      // overrides
      onerror, 
      validatorTypeboxOptions

    },
  },
  function (req, res) {
    // ...
  }
)

References

0.1.3

8 months ago

0.1.2

8 months ago

0.1.1

8 months ago

0.1.0

8 months ago