Skip to content

Commit

Permalink
Decorators: added zod error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
xiduzo committed May 6, 2024
1 parent 8977ca0 commit 7be41e1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 11 deletions.
11 changes: 3 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
{
"name": "aws-lambda-handyman",
"version": "0.5.10",
"version": "0.5.11",
"description": "AWS Lambda TypeScript validation made easy 🏄",
"main": "./lib/cjs/src/index.js",
"typings": "./lib/types/src/index.d.ts",
"module": "./lib/es2015/src/index.js",
"es2015": "./lib/es2015/src/index.js",
"files": [
"lib"
],
"authors": [
"Slaven Ivanov <[email protected]>",
"Sander Boer <[email protected]>"
],
"files": ["lib"],
"authors": ["Slaven Ivanov <[email protected]>", "Sander Boer <[email protected]>"],
"license": "ISC",
"repository": {
"type": "git",
Expand Down
11 changes: 8 additions & 3 deletions src/Decorators.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEventBase, Context } from 'aws-lambda'
import { ClassConstructor, plainToInstance } from 'class-transformer'
import { ValidationError, validateSync } from 'class-validator'
import { validateSync, ValidationError } from 'class-validator'
import 'reflect-metadata'
import { ZodSchema } from 'zod'
import { HttpError, TransformValidateOptions, badRequest, internalServerError, response } from '.'
import { ZodError, ZodSchema } from 'zod'
import { badRequest, HttpError, internalServerError, response, TransformValidateOptions } from '.'

const eventMetadataKey = Symbol('Event')
const contextMetadataKey = Symbol('Ctx')
Expand Down Expand Up @@ -120,6 +120,7 @@ export function Handler(options: TransformValidateOptions = defaultHandlerOption
})
} catch (e) {
if (e instanceof Array && e?.[0] instanceof ValidationError) return badRequest({ message: validationErrorsToMessage(e) })
if (e instanceof ZodError) return badRequest({ message: zodErrorToMessage(e) })

console.error('Oops 😬', e)
if (e instanceof TypeError && e.message === `Cannot read properties of undefined (reading 'catch')`) throw new Error(handlerNotAsyncMessage)
Expand Down Expand Up @@ -157,6 +158,10 @@ function validationErrorsToMessage(errors: ValidationError[]) {
return errors.map((e) => getConstraints(e).join(', ')).join('. ') + '.'
}

function zodErrorToMessage(error: ZodError) {
return error.errors.map((e) => `${e.path.join(' -> ')}: ${e.message}`).join(', ') + '.'
}

function getConstraints(error: ValidationError): string[] {
if (!error.children || !error.children.length) {
return Object.values(error.constraints || [])
Expand Down

0 comments on commit 7be41e1

Please sign in to comment.