3

I'm updating an existing project from V2 to V3 of the AWS SDK for JavaScript and also moving our usage from JavaScript to TypeScript.

I'm struggling to define strongly typed handlers for the Lamdas.

The examples I've found are similar to this. I'm guessing that they're using V2 of the SDK.

export const lambdaHandler = async (event: APIGatewayEvent, context: Context): Promise<APIGatewayProxyResult> => {
    return {
        statusCode: 200,
        body: JSON.stringify({
            message: 'hello world',
        }),
    };
};

I've had a look through the V3 source for classes similar to APIGatewayEvent, Context and APIGatewayProxyResult but nothing jumps out at me as filling those roles.

Can someone please tell me how to strongly type these signatures?

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
Damien Sawyer
  • 5,323
  • 3
  • 44
  • 56

2 Answers2

5

AWS introduced the @types/aws-lambda package for use with there Javascript V3 SDK. Here is a typescript example, for your exact use case.

import { APIGatewayProxyHandler, APIGatewayEvent, APIGatewayProxyResult } from "aws-lambda";

export const handler: APIGatewayProxyHandler = async (event: APIGatewayEvent): Promise<APIGatewayProxyResult> => {
    return {statusCode: 200, body: event.body ?? ''};
}
rocketman
  • 131
  • 1
  • 9
0

I've been looking at this and come up with the following:

import {HttpRequest as __HttpRequest,} from "@aws-sdk/protocol-http";
export const handler = async (
    eventIn: { Records: { body: string }[] },
    context: __HttpRequest
) => {}

Note that I only implemented body, but of course you could put messageId, receiptHandle etc at the same level.

Using this turns out the following

export type EventIn = {
  Records: Array<{
    messageId: string
    receiptHandle: string
    body: string
    attributes: {
      ApproximateReceiveCount: string
      SentTimestamp: string
      SenderId: string
      ApproximateFirstReceiveTimestamp: string
    }
    messageAttributes: {}
    md5OfBody: string
    eventSource: string
    eventSourceARN: string
    awsRegion: string
  }>
}
Damien Sawyer
  • 5,323
  • 3
  • 44
  • 56