AWS TypeScript CDK and Lambda

This quick tutorial will show the steps for deploying a TypeScript lambda that is deployed behind API Gateway and can be used to calculate the sum of 2 numbers. This is an introductory tutorial and…

image

Photo by Joshua Reddekopp on Unsplash

This quick tutorial will show the steps for deploying a TypeScript lambda that is deployed behind API Gateway and can be used to calculate the sum of 2 numbers. This is an introductory tutorial and more work would be needed to make this production-ready but this tutorial will hopefully get you on your way.

Step 1: Install AWS CLI

Follow the steps on the following AWS Page to install the AWS — https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html If the AWS CLI install is successful, running the following command should yield results

aws --version

This should output results similar to the following (dependent on your OS and the version of the AWS CLI installed). If the AWS CLI is not installed successfully, you will get a warning message

aws-cli/2.1.16
Step 2: Configure the AWS CLI

Follow the steps on the following AWS Page to configure the AWS CLI — https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config This is important as it tells the AWS CLI which AWS account and region to use.

Step 3: Install Node.js

Node.js is required as this is a TypeScript project and we will be using the TypeScript CDK. Install Node.js by following the instructions on the Node.js website — https://nodejs.org/en/ Running the following command:

node --version

Should yield results similar to the following (dependent on your OS and the version of node installed)

v14.17.3
Step 4: Install the AWS CDK

The AWS TypeScript CDK is required to work with the CDK. Run the following command to install the CDK

npm install -g aws-cdk

To validate the CDK is installed correctly, run the following command

cdk --version

This should yield results similar to the following (dependent on your OS and CDK version installed)

1.115.0 (build f0ca40f)
Step 5: Setup CDK Project

Run the following command to create a new folder and cd into it

mkdir calculator-lambda && cd calculator-lambda

Run the following command to initiate the CDK project

cdk init app --language typescript

In a separate terminal window, run the watch command which will keep track of changes as we make them to the project

npm run watch
Step 6: Install Lambda Construct

The AWS CDK Lambda construct is required as we want to deploy a Lambda to our AWS accounts. To install the aws-lambda construct, run the following command

npm install @aws-cdk/aws-lambda
Step 7: Create Calculator Lambda

Create a folder in the root of your project (same level as bin and lib) called lambda. Add a file to the lambda folder called calculator.js (lambda/calculator.js) Inside calculator.js — add the following content

exports.handler = async function (event) {
  let num1 = 5;
  let num2 = 10;
  let operation = "addition";
  let result = 0;
  if (event.queryStringParameters && event.queryStringParameters.num1) {
    console.log("num1: " + event.queryStringParameters.num1);
    num1 = parseInt(event.queryStringParameters.num1);
  }

  if (event.queryStringParameters && event.queryStringParameters.num2) {
    console.log("num2: " + event.queryStringParameters.num2);
    num2 = parseInt(event.queryStringParameters.num2);
  }
  if (event.queryStringParameters && event.queryStringParameters.operation) {
    console.log("operation: " + event.queryStringParameters.operation);
    operation = event.queryStringParameters.operation;
  }
  switch (operation) {
    case "multiplication": {
      result = num1 * num2;
      break;
    }
    case "division": {
      result = num1 / num2;
      break;
    }
    case "subtraction": {
      result = num1 - num2;
      break;
    }
    case "addition": {
      result = num1 + num2;
      break;
    }
    default: {
      result = num1 + num2;
      break;
    }
  }
  console.log("Result: " + result);
  return {
    statusCode: 200,
    headers: { "Content-Type": "text/plain" },
    body: result,
  };
};

This code is purely to demo the functionality offered by the CDK and deploying a lambda. If no operation is passed, the addition operation is performed. If no numbers are passed, the default numbers of 5 and 10 are used. Again, more work is required to make this code production ready.

Step 8: Add Lambda to the stack

We have now added our lambda code, but as of yet, it will not be picked up by the CDK. In your favourite text editor, open the file lib/calculator-lambda-stack.ts At the top of the file, add the aws-lambda construct import below the aws-cdk/core import by adding this line

import * as lambda from "@aws-cdk/aws-lambda";

Replace the line:

// The code that defines your stack goes here

With the following code:

const calculator = new lambda.Function(this, "CalculatorHandler", {
  runtime: lambda.Runtime.NODEJS_14_X,
  code: lambda.Code.fromAsset("lambda"),
  handler: "calculator.handler",
});

This code tells the CDK to deploy the lambda that we previously created to our AWS Account.

Step 9: Install API Gateway

The API Gateway is used to call the calculator functionality from our browsers or a tool like Postman. In order to be able to use the API Gateway, we need to install the cdk construct for the API Gateway. That can be installed by running the following command

npm install @aws-cdk/aws-apigateway

In your favourite text editor, open the file lib/calculator-lambda-stack.ts At the top of the file, add the aws-apigateway construct import below the aws-lambda import by adding this line

import * as apigw from "@aws-cdk/aws-apigateway";

In order for the CDK to deploy to API Gateway, we need to reference it in the calculator-lambda-stack.ts file. Below where we defined the calculator lambda function — add the following code.

new apigw.LambdaRestApi(this, "Endpoint", {
  handler: calculator,
});

The final version of calculator-lambda-stack.ts should look like this

import * as cdk from "@aws-cdk/core";
import * as lambda from "@aws-cdk/aws-lambda";
import * as apigw from "@aws-cdk/aws-apigateway";
export class CalculatorLambdaStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    const calculator = new lambda.Function(this, "CalculatorHandler", {
      runtime: lambda.Runtime.NODEJS_14_X,
      code: lambda.Code.fromAsset("lambda"),
      handler: "calculator.handler",
    });
    new apigw.LambdaRestApi(this, "Endpoint", {
      handler: calculator,
    });
  }
}
Step 10: Setup AWS Environment For CDK

The very first time you install a CDK stack to an AWS environment, you need to set it up with a bootstrap stack. This stack can be installed by running the following command

cdk bootstrap
Step 11: Deploy Calculator lambda to AWS Account

This step will take all the code we just worked with and deploy it to our AWS Account. We simply need to just run the following command to tell the CDK to deploy our changes

cdk deploy

When prompted to accept the changes — enter y If the deploy is successful — you should see output similar to the following (urls will be different for every user)

Outputs:
CalculatorLambdaStack.Endpoint8024A810 = <https://cm8mcvb9g4.execute-api.us-east-1.amazonaws.com/prod/>

Take note of the CalculatorLambdaStack.Endpoint as this will be used in the next section for testing.

Step 12: Test functionality

In this section, we will use the API Gateway endpoint we obtained in the last step. These next steps require that you Default: No operation, num1 or num2 specified — the addition operation, num1=5 and num2=10 will be used

Step 13: Delete AWS Resources

Now that this tutorial is complete, you may want to remove the resources in order to keep your AWS account tidy. To delete all generated AWS resources from your account, run the following command

cdk destroy

When prompted to accept that you want to delete the resources — enter y

Conclusion

This tutorial showed how to set up the AWS TypeScript CDK and deploy a calculator service to AWS Lambda which is fronted by API gateway. As mentioned at the start, this code is not production-ready and is just an intro tutorial. If you wish to view the code for this tutorial — it is available here — https://github.com/damogallagher/typescript-lambda-cdk

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics