middy-middleware-class-validator
TypeScript icon, indicating that this package has built-in type declarations

2.0.2 • Public • Published

middy-middleware-class-validator

npm version downloads open issues FOSSA Status debug build status codecov dependency status devDependency status semantic release Gitter

A middy middleware that returns errors as http errors, compatible with http-errors.

Installation

Download node at nodejs.org and install it, if you haven't already.

npm install middy-middleware-class-validator --save

Documentation

There is additional documentation.

Usage

// When using decorators, don't forget to import this in the very first line of code
import 'reflect-metadata'
 
import { APIGatewayProxyEvent } from 'aws-lambda'
import { IsString } from 'class-validator'
import middy from '@middy/core'
import JSONErrorHandlerMiddleware from 'middy-middleware-json-error-handler'
 
import ClassValidatorMiddleware, { WithBody } from 'middy-middleware-class-validator'
 
// Define a validator for the body via class-validator
class NameBody {
  @IsString()
  public firstName: string
 
  @IsString()
  public lastName: string
}
 
// This is your AWS handler
async function helloWorld (event: WithBody<APIGatewayProxyEvent, NameBody>) {
  // Thanks to the validation middleware you can be sure body is typed correctly
  return {
    body: `Hello ${event.body.firstName} ${event.body.lastName}`,
    headers: {
      'content-type': 'text'
    },
    statusCode: 200
  }
}
 
// Let's "middyfy" our handler, then we will be able to attach middlewares to it
export const handler = middy(helloWorld)
  .use(ClassValidatorMiddleware({
    // Add the validation class here
    classType: NameBody
  }))
  // The class validator throws validation errors from http-errors which are compatible with
  // the error handler middlewares for middy
  .use(JSONErrorHandlerMiddleware())

Dependencies (6)

Dev Dependencies (40)

Package Sidebar

Install

npm i middy-middleware-class-validator

Weekly Downloads

86

Version

2.0.2

License

MIT

Unpacked Size

16.7 kB

Total Files

16

Last publish

Collaborators

  • dbartholomae