Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Deploy a Typescript Lambda Function with AWS CDK and a Deno Layer

0.00/5 (No votes)
24 Nov 2020 1  
How to build and deploy a Typescript lambda function with AWS CDK and Deno layer
This is a quick glance at using CDK to create a layer and use it with a lambda function and API gateway.
  • AWS CDK npm install -g aws-cdk
  • Node.js - Download Link
  • An AWS account
  • Local credentials (unless using Cloud 9)
  • jq Download Link (not required, but very useful)

Overview

This is an example project showing:

  • AWS CDK
  • TypeScript
  • Deploying a new layer in a CDK project and deploy a function that will use the layer.

Introduction

I have been following Deno for a little while. It's nice to use strong typing in JavaScript, however the transpilers are a slight overhead. Deno does away with this and allows the use of TypeScript without compilation.

The CDK stack project is still using TypeScript that is compiled, however you can see in tsconfig.json that /src/program is excluded meaning we don't need to compile test files.

Stack

The stack consists of:

  • Lambda layer that enables Deno runtime
  • A Lambda function
  • An API gateway

To start off, clone the repo and cd into the folder, then run:

BAT
npm install
npm run watch

This will start monitoring the CDK stack TypeScript files and compile them to vanilla JavaScript. Keep an eye on the terminal as it will compile the stack code as you make changes and save, and you'll be able to spot mistakes pre runtime.

Layers in CDK

How do we define a layer in CDK? I decided not to build the runtime in this example but show how to deploy a built runtime. I took the latest release from https://github.com/hayd/deno-lambda/releases and unzipped the contents into src/layer folder. These files are what is required to run Demo. In CDK, we define a new layer:

tscript
const layer = new lambda.LayerVersion(this, 'deno-layer', {
    code: lambda.Code.fromAsset('src/layer'),
    compatibleRuntimes: [lambda.Runtime.PROVIDED],
    license: 'Apache-2.0',
    description: 'A layer that enables Deno to run in AWS Lambda',
});

Lambda Function

We can see that AWS provides the lambda.Runtime.PROVIDED value for use when we are leveraging a custom runtime. The code will come from src/program folder, in this case, a single file called name.ts. This file is directly deployed as a TypeScript file. When we create the function, we pass in the layer defined above (that value will be the ARN of the layer). The handler is the name of the file (e.g., name).

tscript
const name = new lambda.Function(this, 'NameHandler', {
      runtime: lambda.Runtime.PROVIDED,
      code: lambda.Code.fromAsset('src/program'),
      handler: 'name.handler',
      layers: layer,
    })

API Gateway

tscript
// API Gateway 
new apigw.LambdaRestApi(this, 'Endpoint', {
  handler: name
});

Sample App

The sample program is very simple. Using the good old Object Oriented "Person" example, we create a person, it shows private variables, and the use of a getter and a constructor.

tscript
import {
    APIGatewayProxyEvent,
    APIGatewayProxyResult,
    Context
} from "https://deno.land/x/lambda/mod.ts";

export async function handler(
  event: APIGatewayProxyEvent,
  context: Context
): Promise<APIGatewayProxyResult> {
  return {
    statusCode: 200,
    headers: { "Content-Type": "text/json" },
    body: JSON.stringify(constructResponse(event)),
  };
}

class Person {
  private _fullName: string;
  get fullName(): string {
    return this._fullName + '!';
  }
  constructor(firstName: string, ) {
      this._fullName = firstName;
  }
}

class Result {
  user: Person;
  message: string;
  constructor(u: Person, m: string){
    this.message = m;
    this.user = u;
  }
}

const constructResponse = (event: APIGatewayProxyEvent) => {
  let name = event.path.replace("/","");
  let p = new Person(name);
  let r = new Result(p, `Hi <span class="pl-kos">${p.fullName}, 
          Welcome to deno ${Deno.version.deno} 🦕`</span>);

  return r;
}

Deploy

When you are ready to deploy, run cdk bootstrap then cdk deploy.

Outputs will look like:

 ✅  CdkOneStack

Outputs:
CdkOneStack.Endpoint8024A810 = https://your-url/prod/

CdkOneStack is defined in:/bin/cdk-one.ts. You can change the name of the stack if you desire:

tscript
import * as cdk from '@aws-cdk/core';
import { CdkOneStack } from '../lib/cdk-one-stack';

const app = new cdk.App();
new CdkOneStack(app, 'CdkOneStack');  // <- Stack name>

Call Your Function!

You can call this by issuing the command:

BAT
curl https://your-url/prod/Your-Name-Here | jq
JSON
{
  "message": "Hi Your-Name-Here!, Welcome to deno 1.0.2 🦕",
  "user": {
    "_fullName": "Your-Name-Here"
  }
}

Video

The cdk.json file tells the CDK Toolkit how to execute your app.

Useful Commands

  • npm run build compiles typescript to js
  • npm run watch watches for changes and compiles
  • cdk deploy deploys this stack to your default AWS account/region
  • cdk diff compares deployed stack with current state
  • cdk synth emits the synthesized CloudFormation template

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here