Skip to content

Bug: Event handler response validation typing issues #5124

@nateiler

Description

@nateiler

Expected Behavior

When performing response body validation for a schema where the input doesn't match the output (coerce) a typing error occurs.

Current Behavior

A schema such as z.object({ id: z.coerce.string(), name: z.string() }) would throw a type error because the input doesn't match the output.

Image

Code snippet

These tests are technically successful, however they illustrate the type error:

it('validates a coerced response object successfully', async () => {
    // Prepare
    const responseSchema = z.object({ id: z.coerce.string(), name: z.string() });

    app.get(
      '/users/:id',
      () => {
        return { id: 123, name: 'John' };
      },
      {
        validation: { res: { body: responseSchema } },
      }
    );

    const event = createTestEvent('/users/123', 'GET', {});
    event.pathParameters = { id: '123' };

    // Act
    const result = await app.resolve(event, context);

    // Assess
    expect(result.statusCode).toBe(200);
  });

It would also be great to allow a response object too:

it('validates response object successfully', async () => {
    // Prepare
    const responseSchema = z.object({ id: z.coerce.string(), name: z.string() });

    app.get(
      '/users/:id',
      () => {
        return Response.json({ id: 123, name: 'John' });
      },
      {
        validation: { res: { body: responseSchema } },
      }
    );

    const event = createTestEvent('/users/123', 'GET', {});
    event.pathParameters = { id: '123' };

    // Act
    const result = await app.resolve(event, context);

    // Assess
    expect(result.statusCode).toBe(200);
  });

Steps to Reproduce

Drop those tests in validation.test.ts

Possible Solution

The TypedRouteHandler could be extended to this:

type TypedRouteHandler<
  TEnv extends Env = Env,
  TReq extends ReqSchema = ReqSchema,
  TResBody extends HandlerResponse = HandlerResponse,
  TRes extends ResSchema = ResSchema,
> = (
  reqCtx: TypedRequestContext<TEnv, TReq, TRes>
) =>
  | Promise<TResBody | ExtendedAPIGatewayProxyResult<TResBody> | Response>
  | TResBody
  | ExtendedAPIGatewayProxyResult<TResBody>
  | Response;

Powertools for AWS Lambda (TypeScript) version

latest

AWS Lambda function runtime

24.x

Packaging format used

npm

Execution logs

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtriageThis item has not been triaged by a maintainer, please wait

    Type

    No type

    Projects

    Status

    Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions