How to work with Lambdas (in the best way!)

Jonas Grøndahl
Oct 1, 2020 · 4 min read

If you have had some rough experiences working with lambdas in the past, you are not only one! In this post, I will show you how I and some of the engineering team at The LEGO Group work with lambdas without getting gray hair along the way.

When getting started with a lambda project, it can be very tempting to pop open the AWS console, navigate to the lambda service page and start writing your Node.js or whatever it may be in there. This is where, I will tell you to stop and take a deep breath — and do this instead:

mkdir cooltechblogcd cooltechblognpx cdk init sample-app --language typescriptnpm install -E @aws-cdk/aws-lambda

This will create a CDK (Cloud Development Kit) project which will allow us to write code locally and deploy our lambda function from our editor. Another advantage of creating a project and write code locally is that everything is in version control right from the start.

The folder structure that the cdk init command creates for us can be a little confusing at first, especially the naming of the folders lib and bin — where to begin?

But before worrying about any of that, let’s add a few modifications to our tsconfig.json file, so we at least have a very basic and functional TypeScript setup with one folder for the output (the JavaScript) and one for the source (TypeScript).

Firstly, add these 3 changes inside compilerOptions:

+ “declaration”: false,+ “rootDir”: “src”,+ “outDir”: “lib”

Create a new folder src in the root and move the bin, lib and test folders inside src.

Great! Let’s create a new file neat.ts for the lambda:

cd src/libmkdir lambdas && cd lambdastouch neat.ts

In this file, we can create our lambda function. If you don’t have too much experience with lambdas, you probably forgot how a lambda is structured at the very basic level — me too…

However, this is how it looks:

export const handler = async (request: any, context: any) => {    return {          statusCode: 200,          body: {              message: “Oh hoy lads”,           },    };};

We are not doing much in here other than returning a response with status code 200 and a body. No cool TypeScript type checking, third party libraries, fireworks and things like that — BUT when we decide to expand on the code later, we are already in a good spot.

Note: Also, we have some any type declarations in there, not pretty BUT we don’t really know how these parameters look beforehand — it depends on the context of where and how the lambda is called.

Now the next step is to deploy our lambda, and this is where the CDK documentation is useful. I’ll show how it’s done, however, be prepared you will use it in the future!

Previously, I mentioned the bin and the lib folder, very confusing names I must say. But don’t worry, at least don’t worry about the bin folder, all that’s in there is a file techblog.ts that has a reference to our stack in the lib/techblog-stack.ts file, and this is where we’ll create our lambda as follows:

import * as cdk from “@aws-cdk/core”;import * as lambda from “@aws-cdk/aws-lambda”;
export class TechblogStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string) { super(scope, id); const fn = new lambda.Function(this, “MyFunction”, { runtime: lambda.Runtime.NODEJS_12_X, handler: “index.handler”, code: lambda.Code.fromAsset(“./lambdas”) }); }
}

Woohoo yay, we did it! BUT before celebrating, we need to make sure our TS code is compiled to JavaScript before running the deploy command.

Something that I like to do is to open an extra terminal window in VSCode and run npm run watch, so my TS code is compiled at all times, and I’m alerted of warnings as we go.

Now for the deployment command:

npx cdk deploy --app lib/bin/techblog.js

At this point, you might get an error message since you are not logged in to AWS, to login use the command aws configure.

And that’s all, you’ve deployed your lambda function to AWS, and you didn’t leave your editor. Last note, a common use case is to pull in third-party dependencies in your lambda function to use. To do so you can do npm init inside your lambda folder and start pulling packages with npm install.

Quick disclaimer, since you are in TypeScript world remember to add some logic in your CDK code to do an npm install of your npm packages before bundling the lambda code, since these are not transferred over when compiling your TS code to JS.

That’s all for now, hope you learned a thing or two.

By Jonas Grøndahl
Senior IT Engineer, The LEGO Group

About me:
Jonas Grøndahl is a Senior IT Engineer at The LEGO Group, holds a bachelor’s in Computer Science from University of Southern Denmark and has over 5 years of practical experience. He works mostly within the JavaScript, TypeScript, React, React Native, AWS ecosystem. He enjoys traveling, video games, creates YouTube videos and is currently learning Chinese.

Destination AARhus-TechBlog

Engineers sharing knowledge and insights into current IT challenges, development and features.

Destination AARhus-TechBlog

A team of IT and digital experts from Greater Aarhus, Denmark — sharing ideas, knowledge and insights. Are you a passionate engineer? Check out the many career opportunities of our business network here: https://destinationaarhus.com/vacant-positions/

Jonas Grøndahl

Written by

Destination AARhus-TechBlog

A team of IT and digital experts from Greater Aarhus, Denmark — sharing ideas, knowledge and insights. Are you a passionate engineer? Check out the many career opportunities of our business network here: https://destinationaarhus.com/vacant-positions/