Lambda Events & Typescript

Lambda Events & Typescript

Adding types to serverless events

Adding types to serverless event handlers can help us easily navigate the serverless (and by serverless, I mean to limit myself to AWS Lambda here) world without peeking over at the docs every time. And what's even better is that the type-system already comes with the AWS SDK. Just that it's hidden and kind of thus never discussed about.

To get started install the library: npm install --save-dev aws-sdk @types/aws-lambda or yarn add --dev aws-sdk @types/aws-lambda.

Pro-tip: aws-sdk is already provided in Lambda environments when deployed. Hence adding it as a development dependency keeps the size of production dependencies smaller thus making deployment packages to Lambda functions and/or layers smaller.

Then in the event handler file, we can start adding types as follows:

import { SQSEvent, SQSHandler } from 'aws-lambda';

interface MyInterface {
    field1: string;
    field2: number
}

const handler: SQSHandler = async (event: SQSEvent) => {

  // Lambda uses an internal poller to retrieve events in from sources like SQS, hence the loop
  for (const record of event.Records) {
    const message = JSON.parse(record.) as MyInterface; // Define exact message fields in this interface
    console.log(message);
  }
}

The advantage of using TypeScript in this instance is that we get IntelliSense when using VS Code for accessing event properties.

Screenshot 2021-07-18 at 5.20.32 AM.png

And this is the first step towards googling less stuff related to AWS's documentation! It will become lesser and lesser as we become more familiar with it. Similar events can be added for other Lambda trigger events too. Here's one for S3 -

const s3EventHandler: S3Handler = async (event: S3Event) => {
  for (const record of event.Records) {
    const filename = JSON.parse(record.s3.object.key);
    console.log(filename);
  }
}

For SNS, as you might have expected, the snippet will look similar to that of SQS -

const snsEventHandler: SNSHandler = async (event: SNSEvent) => {
  for (const record of event.Records) {
    const message = JSON.parse(record.body) as AnotherInterface;
    console.log(message);
  }
}

Happy coding!