dbartholomae / lambda-middleware

A collection of middleware for AWS lambda functions.
https://dbartholomae.github.io/lambda-middleware/
MIT License
151 stars 18 forks source link

class-validator seems to break the type inference for the handler #60

Closed ghost closed 2 years ago

ghost commented 2 years ago

Describe the bug

When classValidator is used in composeHandler, the types for event, and context becomes any. The return type is lost as well.

To Reproduce

The following minimal code reproduces the error:

import "reflect-metadata"
import { composeHandler } from "@lambda-middleware/compose"
import { jsonSerializer } from "@lambda-middleware/json-serializer"
import { errorHandler } from "@lambda-middleware/http-error-handler"
import { classValidator } from '@lambda-middleware/class-validator'
import { jsonDeserializer } from "@lambda-middleware/json-deserializer"
import { doNotWait } from "@lambda-middleware/do-not-wait"
import { IsString } from "class-validator"

class NameBody {
      constructor(firstName: string, lastName: string) {
            this.firstName = firstName;
            this.lastName = lastName;
      }

      @IsString()
      public firstName: string;

      @IsString()
      public lastName: string;
}

export const handler = composeHandler(
      errorHandler(),
      doNotWait(),
      jsonDeserializer(),
      jsonSerializer(),
      classValidator({
            bodyType: NameBody,
      }),
      async (evt, ctx) => {
            return {

            }
      }
)

Expected behavior

A clear and concise description of what you expected to happen. Infer event, context, and return type.

Additional context

Here is a screenshot from the code snippet, it weirdly expects a then: image

dbartholomae commented 2 years ago

Thanks! You will have to explicitly type evt and ctx. TypeScript will then complain if the type doesn't match with what classValidator returns. The reason why then is suggested is that this is an asynchronous function which needs to return a Promise.