Click here to Skip to main content
15,884,298 members
Articles / Hosted Services / AWS

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
24 Nov 2020CPOL2 min read 20.9K   2   2   4
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
This article was originally posted at https://github.com/kukielp/deno-lambda-cdk

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
SAMManjula23-Nov-20 19:58
SAMManjula23-Nov-20 19:58 
QuestionNice work Pin
peterkmx20-Jun-20 23:19
professionalpeterkmx20-Jun-20 23:19 
AnswerRe: Nice work Pin
PaulKukiel21-Jun-20 0:07
PaulKukiel21-Jun-20 0:07 
GeneralRe: Nice work Pin
peterkmx21-Jun-20 1:20
professionalpeterkmx21-Jun-20 1:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.