Intro

In the previous article we discussed one way to create TypeScript aws lambda using SAM (Serverless Application Model). There we talked about a few manual steps to convert existing javascript code into typescript.

In the current article we’ll take a look at even easier way to achieve the same. We will use sam cli only. It maybe one of the fastest and easiest way to create typescript aws lambda.

Steps to create TypeScript lambda using sam cli

Initiate aws lambda structure using SAM

Just like in the previous article we will use the following command to initiate our TypeScript lambda.

sam init

This time when sam cli asks for AWS quick start application templates we choose option 8: Quick Start: App Backend using TypeScript

sam init output

As a result the following structure will be created: folder's structure

Check generated folder and update logic according to your need

When we check package.json file in app folder we will see something like this:

{
  "name": "web_template",
  "version": "1.0.0",
  "author": "SAM CLI",
  "license": "MIT",
  "directories": {
    "test": "tests"
  },
  "scripts": {
    "fast-compile": "tsc",
    "compile": "eslint . --ext .ts && tsc",
    "lint": "eslint . --ext .ts",
    "test": "eslint . --ext .ts && tsc && mocha",
    "fast-test": "mocha"
  },
  "devDependencies": {
    "@types/chai": "^4.2.14",
    "@types/mocha": "^8.2.0",
    "@types/node": "^14.14.13",
    "@typescript-eslint/eslint-plugin": "^4.9.1",
    "@typescript-eslint/parser": "^4.9.1",
    "chai": "^4.2.0",
    "eslint": "^7.15.0",
    "mocha": "^8.2.1",
    "moq.ts": "^6.4.0",
    "ts-node": "^9.1.1",
    "typescript": "^4.1.3"
  },
  "dependencies": {
    "aws-sdk": "^2.809.0"
  }
}

As you can see there are already scripts for testing!, compilation and linting. It’s very handy to have everything in place already, right? :-).

Even more:

  • there are examples of handlers in app/src/handlers
  • mocha unit tests in app/tests/apps that can help you be up to speed really fast
  • interfaces that are useful for testing and general understanding of aws api gateway structure in app/src/common/apigateway (although the same classes you can use from aws libraries by installing @types/aws-lambda npm package, which is much more reliable)
  • last, but not least, an example of dynamoDbRepository which is pretty basic though

Apart from source code you can find Makefile that makes it easy to build your source code and be prepared for deployment.

And with everything said above you can run the following commands to deploy your lambda to aws account:

sam build
sam deploy --guided

Conclusion

SAM makes it super easy to create aws typescript lambda and along the way provides a good starting point for active development.

Updated: