├── .gitignore ├── .vscode └── launch.json ├── LICENSE ├── Makefile ├── Procfile ├── README.md ├── __tests__ ├── unit │ └── handlers │ │ ├── get-all-items.test.ts │ │ ├── get-by-id.test.ts │ │ ├── put-item.test.ts │ │ └── write-item.test.ts └── utils │ └── helpers.ts ├── buildspec.yml ├── env.json.sample ├── events ├── event-get-all-items.json ├── event-get-by-id.json └── event-post-item.json ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── handlers │ ├── get-all-items.ts │ ├── get-by-id.ts │ ├── put-item.ts │ └── write-item.ts └── utils │ ├── dynamodb.ts │ └── sqs.ts ├── template.yml └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .aws-sam 3 | samconfig.toml 4 | env.json 5 | dist/ 6 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Attach to SAM CLI", 6 | "type": "node", 7 | "request": "attach", 8 | "address": "localhost", 9 | "port": 5858, 10 | "localRoot": "${workspaceRoot}/", 11 | "remoteRoot": "/var/task", 12 | "protocol": "inspector", 13 | "stopOnEntry": false 14 | } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2021 Andrey Novikov 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build-RuntimeDependenciesLayer build-lambda-common 2 | .PHONY: build-getAllItemsFunction build-getByIdFunction build-putItemFunction 3 | 4 | build-getAllItemsFunction: 5 | $(MAKE) HANDLER=src/handlers/get-all-items.ts build-lambda-common 6 | build-getByIdFunction: 7 | $(MAKE) HANDLER=src/handlers/get-by-id.ts build-lambda-common 8 | build-putItemFunction: 9 | $(MAKE) HANDLER=src/handlers/put-item.ts build-lambda-common 10 | build-writeItemFunction: 11 | $(MAKE) HANDLER=src/handlers/write-item.ts build-lambda-common 12 | 13 | build-lambda-common: 14 | npm install 15 | rm -rf dist 16 | printf "{\"extends\": \"./tsconfig.json\", \"include\": [\"${HANDLER}\"] }" > tsconfig-only-handler.json 17 | npm run build -- --build tsconfig-only-handler.json 18 | cp -r dist "$(ARTIFACTS_DIR)/" 19 | 20 | build-RuntimeDependenciesLayer: 21 | mkdir -p "$(ARTIFACTS_DIR)/nodejs" 22 | cp package.json package-lock.json "$(ARTIFACTS_DIR)/nodejs/" 23 | npm install --production --prefix "$(ARTIFACTS_DIR)/nodejs/" 24 | rm "$(ARTIFACTS_DIR)/nodejs/package.json" 25 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | sam: sam local start-api --env-vars=env.json 2>&1 | tr "\r" "\n" #workaround for stdout corruption https://github.com/aws/aws-lambda-runtime-interface-emulator/issues/15#issuecomment-792448261 2 | tsc: npm run watch 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-sam-typescript-layers-example 2 | 3 | This project contains source code and supporting files for a serverless application that is written in TypeSctipt using shared layers for dependencies with following considerations in mind: 4 | 5 | - Keeping the local development experience mostly unchanged compared to pure Node.js SAM app: no moving `package.json` to other places or otherwise change the directory structure before deployment. 6 | - No running `sam build` on every change in a function handler code. 7 | - Keeping generated JS code as close to TS source as possible, preserving the file layout (don't bundle everything into a single file like webpack does). 8 | - Keeping dependencies in a separate layer shared between related Lambdas: it makes deploys faster as you only need to update function code and not its dependencies. Also, Lambda functions have the size limit which can be easily surpassed with heavy dependencies, shared layers allow us to keep coloring between the lines. 9 | - Keeping deploys as vanilla as possible: `sam build` and `sam deploy`, with no extra CLI magic. 10 | 11 | In short, a Lambda with TypeScript and shared layers must behave the same way as a freshly generated Lambda on pure Node.js. 12 | 13 | To create your own serverless application based this example you can use [this SAM template](https://github.com/Envek/cookiecutter-aws-sam-typescript-layers): 14 | 15 | ```sh 16 | sam init --location gh:Envek/cookiecutter-aws-sam-typescript-layers 17 | ``` 18 | 19 | This sample application is artificially created set of Lambda function that does arbitrary CRUD operations in a way that better display benefits and features of this solution, like partial transpiling of only used source files. 20 | 21 | This repo includes the following files and folders: 22 | 23 | - `src` - Code for the application's Lambda function written in TypeScript. 24 | - `events` - Invocation events that you can use to invoke the function. 25 | - `__tests__` - Unit tests for the application code. 26 | - `template.yml` - A template that defines the application's AWS resources. 27 | 28 | The application uses several AWS resources, including Lambda functions, an API Gateway API, and Amazon DynamoDB tables. These resources are defined in the `template.yml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. 29 | 30 | If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. 31 | The AWS Toolkit is an open-source plugin for popular IDEs that uses the AWS SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds step-through debugging for Lambda function code. 32 | 33 | To get started, see the following: 34 | 35 | * [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) 36 | * [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) 37 | * [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) 38 | * [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) 39 | 40 | ## Deploy the sample application 41 | 42 | The AWS SAM CLI is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. 43 | 44 | To use the AWS SAM CLI, you need the following tools: 45 | 46 | * AWS SAM CLI - [Install the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html). 47 | * Node.js - [Install Node.js 12](https://nodejs.org/en/), including the npm package management tool. 48 | * Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community). 49 | 50 | To build and deploy your application for the first time, run the following in your shell: 51 | 52 | ```bash 53 | sam build 54 | sam deploy --guided 55 | ``` 56 | 57 | The first command will build the source of your application: installs dependencies that are defined in `package.json`, creates a deployment package, and saves it in the `.aws-sam/build` folder. 58 | 59 | The second command will package and deploy your application to AWS, with a series of prompts: 60 | 61 | * **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. 62 | * **AWS Region**: The AWS region you want to deploy your app to. 63 | * **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. 64 | * **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modified IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. 65 | * **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. 66 | 67 | The API Gateway endpoint API will be displayed in the outputs when the deployment is complete. 68 | 69 | ### Building of additional layers and Lambda itself 70 | 71 | To decrease size of Lambda functions, runtime dependencies are extracted into Lambda Layer. 72 | 73 | However, many guides (including Amazon ones) like [1](https://aws.amazon.com/blogs/compute/working-with-aws-lambda-and-lambda-layers-in-aws-sam/) or [2](https://medium.com/@anjanava.biswas/nodejs-runtime-environment-with-aws-lambda-layers-f3914613e20e) propose to move `package.json` to another folder which breaks local development and testing. 74 | 75 | To keep local workflow, building of Lambda itself and its layers was changed from default “automagic” of SAM (`sam build` automatically copies code, installs packages, and cleans up, but this process can't be customized) to explicit steps defined in `Makefile` as per [Building layers](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/building-layers.html) doc. 76 | 77 | So, now on `sam build` command: 78 | 1. Only `src` folder is copied into function itself (however it is renamed into `dist` and contains TypeScript transpiled to JavaScript). 79 | 2. packages are installed into separate layer (`package-lock.json` is also copied for reference) 80 | 3. Local project layout isn't changed at all. 81 | 82 | `sam deploy` will update layer with dependencies only if number or versions of packages were changed. 83 | 84 | ## Use the AWS SAM CLI to build and test locally 85 | 86 | Copy `env.json.sample` to `env.json`: 87 | 88 | ```sh 89 | cp -n env.json{.sample,} 90 | ``` 91 | 92 | Create some DynamoDB table in AWS console at https://console.aws.amazon.com/dynamodb/home#tables: for local development and write its name into `env.json` (make sure that region in your local configuration matches with console). 93 | 94 | **Warning:** Make sure you don't have `.aws-sam` directory (built SAM template), because if you do, `sam local invoke` will use code from it and won't see your code changes. 95 | 96 | If you have some kind of Procfile launcher like [Overmind](https://github.com/DarthSim/overmind) (highly recommended!) you can use it to start both TypeScript compiler in watch mode and local API gateway simultaneously: 97 | 98 | ```bash 99 | $ overmind start 100 | ``` 101 | 102 | And that's it: now you can head over to http://localhost:3000/ to hit `getAllItemsFunction`! 103 | 104 | But, sure, you still can start components independently: 105 | 106 | Start Typescript compiler in watch mode to recompile your code on change (_instead_ of running `sam build` command). 107 | 108 | ```bash 109 | $ npm run watch 110 | ``` 111 | 112 | Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. 113 | 114 | Run functions locally and invoke them with the `sam local invoke` command. 115 | 116 | ```bash 117 | my-application$ sam local invoke putItemFunction --env-vars env.json --event events/event-post-item.json 118 | my-application$ sam local invoke getAllItemsFunction --env-vars env.json --event events/event-get-all-items.json 119 | ``` 120 | 121 | The AWS SAM CLI can also emulate your application's API. Use the `sam local start-api` command to run the API locally on port 3000. 122 | 123 | ```bash 124 | my-application$ sam local start-api --env-vars=env.json 125 | my-application$ curl -X POST http://localhost:3000/ -d '{"id": "curl1","name": "Created with cURL"}' 126 | my-application$ curl http://localhost:3000/ 127 | ``` 128 | 129 | The AWS SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. 130 | 131 | ```yaml 132 | Events: 133 | Api: 134 | Type: Api 135 | Properties: 136 | Path: / 137 | Method: GET 138 | ``` 139 | 140 | ### Debugging 141 | 142 | You can debug with external debugger by this manual: [Step-through debugging Node.js functions locally ](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-debugging-nodejs.html) 143 | 144 | 1. Run `sam local invoke` with `--debug-port` option. 145 | 146 | ```sh 147 | $ sam local invoke getAllItemsFunction --env-vars=env.json --event events/event-get-all-items.json --debug-port 5858 148 | ``` 149 | 150 | It will wait for debugger to attach before starting execution of the function. 151 | 152 | 2. Place a breakpoint where needed (yes, right in TypeScript code). 153 | 154 | 3. Start external debugger. In Visual Studio Code you can just press F5. 155 | 156 | ## Add a resource to your application 157 | The application template uses AWS SAM to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources, such as functions, triggers, and APIs. For resources that aren't included in the [AWS SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use the standard [AWS CloudFormation resource types](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html). 158 | 159 | Update `template.yml` to add a dead-letter queue to your application. In the **Resources** section, add a resource named **MyQueue** with the type **AWS::SQS::Queue**. Then add a property to the **AWS::Serverless::Function** resource named **DeadLetterQueue** that targets the queue's Amazon Resource Name (ARN), and a policy that grants the function permission to access the queue. 160 | 161 | ```yaml 162 | Resources: 163 | MyQueue: 164 | Type: AWS::SQS::Queue 165 | getAllItemsFunction: 166 | Type: AWS::Serverless::Function 167 | Properties: 168 | Handler: src/handlers/get-all-items.getAllItemsHandler 169 | Runtime: nodejs18.x 170 | DeadLetterQueue: 171 | Type: SQS 172 | TargetArn: !GetAtt MyQueue.Arn 173 | Policies: 174 | - SQSSendMessagePolicy: 175 | QueueName: !GetAtt MyQueue.QueueName 176 | ``` 177 | 178 | The dead-letter queue is a location for Lambda to send events that could not be processed. It's only used if you invoke your function asynchronously, but it's useful here to show how you can modify your application's resources and function configuration. 179 | 180 | Deploy the updated application. 181 | 182 | ```bash 183 | my-application$ sam deploy 184 | ``` 185 | 186 | Open the [**Applications**](https://console.aws.amazon.com/lambda/home#/applications) page of the Lambda console, and choose your application. When the deployment completes, view the application resources on the **Overview** tab to see the new resource. Then, choose the function to see the updated configuration that specifies the dead-letter queue. 187 | 188 | ## Fetch, tail, and filter Lambda function logs 189 | 190 | To simplify troubleshooting, the AWS SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs that are generated by your Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. 191 | 192 | **NOTE:** This command works for all Lambda functions, not just the ones you deploy using AWS SAM. 193 | 194 | ```bash 195 | my-application$ sam logs -n putItemFunction --stack-name sam-app --tail 196 | ``` 197 | 198 | **NOTE:** This uses the logical name of the function within the stack. This is the correct name to use when searching logs inside an AWS Lambda function within a CloudFormation stack, even if the deployed function name varies due to CloudFormation's unique resource name generation. 199 | 200 | You can find more information and examples about filtering Lambda function logs in the [AWS SAM CLI documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). 201 | 202 | ## Unit tests 203 | 204 | Tests are defined in the `__tests__` folder in this project. Use `npm` to install the [Jest test framework](https://jestjs.io/) and run unit tests. 205 | 206 | ```bash 207 | my-application$ npm install 208 | my-application$ npm run test 209 | ``` 210 | 211 | ## Cleanup 212 | 213 | To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: 214 | 215 | ```bash 216 | aws cloudformation delete-stack --stack-name aws-sam-typescript-layers-example 217 | ``` 218 | 219 | ## Resources 220 | 221 | For an introduction to the AWS SAM specification, the AWS SAM CLI, and serverless application concepts, see the [AWS SAM Developer Guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html). 222 | 223 | Next, you can use the AWS Serverless Application Repository to deploy ready-to-use apps that go beyond Hello World samples and learn how authors developed their applications. For more information, see the [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) and the [AWS Serverless Application Repository Developer Guide](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/what-is-serverlessrepo.html). 224 | 225 | ## License 226 | 227 | This example is licensed under the terms of the [MIT license](https://opensource.org/licenses/MIT). See [LICENSE](./LICENSE) file for details. 228 | -------------------------------------------------------------------------------- /__tests__/unit/handlers/get-all-items.test.ts: -------------------------------------------------------------------------------- 1 | import { constructAPIGwEvent } from "../../utils/helpers"; 2 | 3 | // Import all functions from get-all-items.js 4 | import { getAllItemsHandler } from '../../../src/handlers/get-all-items'; 5 | // Import dynamodb from aws-sdk 6 | import { DocumentClient } from 'aws-sdk/clients/dynamodb'; 7 | 8 | // This includes all tests for getAllItemsHandler() 9 | describe('Test getAllItemsHandler', () => { 10 | let scanSpy; 11 | 12 | // Test one-time setup and teardown, see more in https://jestjs.io/docs/en/setup-teardown 13 | beforeAll(() => { 14 | // Mock dynamodb get and put methods 15 | // https://jestjs.io/docs/en/jest-object.html#jestspyonobject-methodname 16 | scanSpy = jest.spyOn(DocumentClient.prototype, 'scan'); 17 | }); 18 | 19 | // Clean up mocks 20 | afterAll(() => { 21 | scanSpy.mockRestore(); 22 | }); 23 | 24 | it('should return ids', async () => { 25 | const items = [{ id: 'id1' }, { id: 'id2' }]; 26 | 27 | // Return the specified value whenever the spied scan function is called 28 | scanSpy.mockReturnValue({ 29 | promise: () => Promise.resolve({ Items: items }) 30 | }); 31 | 32 | const event = constructAPIGwEvent({}, { method: 'GET' }); 33 | 34 | // Invoke helloFromLambdaHandler() 35 | const result = await getAllItemsHandler(event); 36 | 37 | const expectedResult = { 38 | statusCode: 200, 39 | body: JSON.stringify(items) 40 | }; 41 | 42 | // Compare the result with the expected result 43 | expect(result).toEqual(expectedResult); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /__tests__/unit/handlers/get-by-id.test.ts: -------------------------------------------------------------------------------- 1 | import { constructAPIGwEvent } from "../../utils/helpers"; 2 | 3 | // Import all functions from get-by-id.js 4 | import { getByIdHandler } from '../../../src/handlers/get-by-id'; 5 | // Import dynamodb from aws-sdk 6 | import { DocumentClient } from 'aws-sdk/clients/dynamodb'; 7 | 8 | // This includes all tests for getByIdHandler() 9 | describe('Test getByIdHandler', () => { 10 | let getSpy; 11 | 12 | // Test one-time setup and teardown, see more in https://jestjs.io/docs/en/setup-teardown 13 | beforeAll(() => { 14 | // Mock dynamodb get and put methods 15 | // https://jestjs.io/docs/en/jest-object.html#jestspyonobject-methodname 16 | getSpy = jest.spyOn(DocumentClient.prototype, 'get'); 17 | }); 18 | 19 | // Clean up mocks 20 | afterAll(() => { 21 | getSpy.mockRestore(); 22 | }); 23 | 24 | // This test invokes getByIdHandler() and compare the result 25 | it('should get item by id', async () => { 26 | const item = { id: 'id1' }; 27 | 28 | // Return the specified value whenever the spied get function is called 29 | getSpy.mockReturnValue({ 30 | promise: () => Promise.resolve({ Item: item }) 31 | }); 32 | 33 | const event = constructAPIGwEvent({}, { 34 | httpMethod: 'GET', 35 | pathParameters: { 36 | id: 'id1' 37 | } 38 | }); 39 | 40 | // Invoke getByIdHandler() 41 | const result = await getByIdHandler(event); 42 | 43 | const expectedResult = { 44 | statusCode: 200, 45 | body: JSON.stringify(item) 46 | }; 47 | 48 | // Compare the result with the expected result 49 | expect(result).toEqual(expectedResult); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /__tests__/unit/handlers/put-item.test.ts: -------------------------------------------------------------------------------- 1 | import { constructAPIGwEvent } from "../../utils/helpers"; 2 | 3 | // Import all functions from put-item.js 4 | import { putItemHandler } from '../../../src/handlers/put-item'; 5 | // Import sqs from aws-sdk 6 | // import SQS from 'aws-sdk/clients/sqs'; 7 | import CustomSqsClient from '../../../src/utils/sqs'; 8 | 9 | // This includes all tests for putItemHandler() 10 | describe('Test putItemHandler', function () { 11 | let putSpy; 12 | 13 | // Test one-time setup and teardown, see more in https://jestjs.io/docs/en/setup-teardown 14 | beforeAll(() => { 15 | // Mock SQS sendMessage method 16 | // https://jestjs.io/docs/en/jest-object.html#jestspyonobject-methodname 17 | // We can't spy on SQS.prototype sendMessage method from aws-sdk and I don't understand why 18 | putSpy = jest.spyOn(CustomSqsClient.prototype, 'send'); 19 | }); 20 | 21 | // Clean up mocks 22 | afterAll(() => { 23 | putSpy.mockRestore(); 24 | }); 25 | 26 | // This test invokes putItemHandler() and compare the result 27 | it('should add id to the SQS queue', async () => { 28 | putSpy.mockReturnValue(Promise.resolve({ MessageId: "5972648d-f5ec-4941-b1bc-1cd890982a22" })); 29 | 30 | const event = constructAPIGwEvent( 31 | { id: "id1", name: "name1" }, 32 | { method: 'POST' }, 33 | ); 34 | 35 | // Invoke putItemHandler() 36 | const result = await putItemHandler(event); 37 | 38 | // Compare the result with the expected result 39 | expect(result.statusCode).toEqual(201); 40 | expect(JSON.parse(result.body)).toMatchObject({ MessageId: "5972648d-f5ec-4941-b1bc-1cd890982a22" }); 41 | expect(putSpy).toHaveBeenCalled(); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /__tests__/unit/handlers/write-item.test.ts: -------------------------------------------------------------------------------- 1 | import { constructSQSEvent } from "../../utils/helpers"; 2 | 3 | // Import all functions from put-item.js 4 | import { writeItemHandler } from '../../../src/handlers/write-item'; 5 | // Import dynamodb from aws-sdk 6 | import dynamodb from 'aws-sdk/clients/dynamodb'; 7 | 8 | // This includes all tests for putItemHandler() 9 | describe('Test writeItemHandler', function () { 10 | let writeSpy; 11 | 12 | // Test one-time setup and teardown, see more in https://jestjs.io/docs/en/setup-teardown 13 | beforeAll(() => { 14 | // Mock dynamodb get and put methods 15 | // https://jestjs.io/docs/en/jest-object.html#jestspyonobject-methodname 16 | writeSpy = jest.spyOn(dynamodb.DocumentClient.prototype, 'put'); 17 | }); 18 | 19 | // Clean up mocks 20 | afterAll(() => { 21 | writeSpy.mockRestore(); 22 | }); 23 | 24 | // This test invokes putItemHandler() and compare the result 25 | it('should add id to the table', async () => { 26 | const returnedItem = { id: 'id1', name: 'name1' }; 27 | 28 | // Return the specified value whenever the spied put function is called 29 | writeSpy.mockReturnValue({ 30 | promise: () => Promise.resolve(returnedItem) 31 | }); 32 | 33 | const event = constructSQSEvent( 34 | { id: "id1", name: "name1" }, 35 | ); 36 | 37 | await writeItemHandler(event); 38 | 39 | expect(writeSpy).toHaveBeenCalled(); 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /__tests__/utils/helpers.ts: -------------------------------------------------------------------------------- 1 | import { APIGatewayProxyEvent, SQSEvent } from "aws-lambda"; 2 | 3 | const DEFAULT_OPTIONS = { method: "GET", headers: {}, query: {}, path: "/" } 4 | 5 | export function constructAPIGwEvent(message: any, options: any = DEFAULT_OPTIONS): APIGatewayProxyEvent { 6 | const opts = Object.assign({}, DEFAULT_OPTIONS, options); 7 | return { 8 | httpMethod: opts.method, 9 | path: opts.path, 10 | queryStringParameters: opts.query, 11 | headers: opts.headers, 12 | body: opts.rawBody || JSON.stringify(message), 13 | multiValueHeaders: {}, 14 | multiValueQueryStringParameters: {}, 15 | isBase64Encoded: false, 16 | pathParameters: opts.pathParameters || {}, 17 | stageVariables: {}, 18 | requestContext: null, 19 | resource: null, 20 | } 21 | } 22 | 23 | export function constructSQSEvent(message: any): SQSEvent { 24 | return { 25 | Records: [ 26 | { 27 | messageId: "d90fd5a5-fd9e-4ab0-979b-97a1e70c9587", 28 | receiptHandle: "AQEB3Z4KHgpG7c/PG+QzcQ8+lfkZTtoS902r67GNes0Oo4JvcaEzkpTYoUzWTtbkhwbrJcxX36YvNW73oJXiNRnZjKHMkv9348JwBfLc9ES32IrK7w2RTXJ+Odl1mMIJCnuYGaiM61HxymbBRn3MmDHiOHqPytTwYSUNsZWP+OZRWncmPTBjyqrdq1/bItRLAtIM02WR6r3S+YyjCYLO0kKlYs0g4JZAEJ7CD8VXvDJnuDTBFPGv+5a9HaJRsxwF1LdksC5YYdEQ7uScKHm0gZFGLHyifN6S2J3x6vzooSR72gmUx1Bu43U3yu2arbwbykaO+40NjfsxK/Z43cXStWIlV+V7ZX5kJ9YTpqkOKujZtmZ4fYZXcns/WYEiwuw9eoPFaSMdVJyFCPScNlsGvfcHc8IkjXC0TbhV68XJYb7eR6Y=", 29 | body: JSON.stringify(message), 30 | attributes: { 31 | ApproximateReceiveCount: "1", 32 | SentTimestamp: "1602074535529", 33 | SenderId: "123456789012", 34 | ApproximateFirstReceiveTimestamp: "1602074535540" 35 | }, 36 | messageAttributes: {}, 37 | md5OfBody: "033bd94b1168d7e4f0d644c3c95e35bf", 38 | eventSource: "aws:sqs", 39 | eventSourceARN: "arn:aws:sqs:us-east-1:123456789012:WriteQueue-KJAGRBTIIB1Y", 40 | awsRegion: "us-east-1" 41 | } 42 | ] 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /buildspec.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | # Install all dependencies (including dependencies for running tests) 6 | - npm install 7 | pre_build: 8 | commands: 9 | # Discover and run unit tests in the '__tests__' directory 10 | - npm run test 11 | # Remove all unit tests to reduce the size of the package that will be ultimately uploaded to Lambda 12 | - rm -rf ./__tests__ 13 | # Remove all dependencies not needed for the Lambda deployment package (the packages from devDependencies in package.json) 14 | - npm prune --production 15 | build: 16 | commands: 17 | # Use AWS SAM to package the application by using AWS CloudFormation 18 | - aws cloudformation package --template template.yml --s3-bucket $S3_BUCKET --output-template template-export.yml 19 | artifacts: 20 | type: zip 21 | files: 22 | - template-export.yml 23 | -------------------------------------------------------------------------------- /env.json.sample: -------------------------------------------------------------------------------- 1 | { 2 | "getAllItemsFunction": { 3 | "SAMPLE_TABLE": "" 4 | }, 5 | "getByIdFunction": { 6 | "SAMPLE_TABLE": "" 7 | }, 8 | "putItemFunction": { 9 | "ITEM_QUEUE": "" 10 | }, 11 | "writeItemFunction": { 12 | "SAMPLE_TABLE": "" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /events/event-get-all-items.json: -------------------------------------------------------------------------------- 1 | { 2 | "httpMethod": "GET" 3 | } -------------------------------------------------------------------------------- /events/event-get-by-id.json: -------------------------------------------------------------------------------- 1 | { 2 | "httpMethod": "GET", 3 | "pathParameters": { 4 | "id": "id1" 5 | } 6 | } -------------------------------------------------------------------------------- /events/event-post-item.json: -------------------------------------------------------------------------------- 1 | { 2 | "httpMethod": "POST", 3 | "body": "{\"id\": \"id1\",\"name\": \"name1\"}" 4 | } -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'node', 4 | modulePathIgnorePatterns: [ 5 | "/.aws-sam", 6 | "/__tests__/fixtures", 7 | "/__tests__/utils", 8 | "/__tests__/global-setup.js", 9 | ], 10 | clearMocks: true, 11 | }; 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "delete-test-01", 3 | "description": "delete-test-01-description", 4 | "version": "0.0.1", 5 | "private": true, 6 | "dependencies": { 7 | "aws-sdk": "^2.437.0", 8 | "source-map-support": "^0.5.19" 9 | }, 10 | "devDependencies": { 11 | "@types/aws-lambda": "^8.10.64", 12 | "@types/jest": "^26.0.14", 13 | "@types/node": "^12.18.4", 14 | "jest": "^26.6.0", 15 | "ts-jest": "^26.4.3", 16 | "ts-node": "^9.0.0", 17 | "typescript": "^4.0.5" 18 | }, 19 | "scripts": { 20 | "build": "npx tsc", 21 | "watch": "node_modules/typescript/bin/tsc -w --preserveWatchOutput", 22 | "test": "jest" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/handlers/get-all-items.ts: -------------------------------------------------------------------------------- 1 | import 'source-map-support/register'; 2 | import { 3 | APIGatewayProxyEvent, 4 | APIGatewayProxyResult 5 | } from "aws-lambda"; 6 | 7 | // Create clients and set shared const values outside of the handler. 8 | import CustomDynamoClient from '../utils/dynamodb'; 9 | 10 | /** 11 | * A simple example includes a HTTP get method to get all items from a DynamoDB table. 12 | */ 13 | export const getAllItemsHandler = async ( 14 | event: APIGatewayProxyEvent, 15 | ): Promise => { 16 | if (event.httpMethod !== 'GET') { 17 | throw new Error(`getAllItems only accept GET method, you tried: ${event.httpMethod}`); 18 | } 19 | // All log statements are written to CloudWatch 20 | console.info('received:', event); 21 | 22 | const client = new CustomDynamoClient(); 23 | const items = await client.readAll(); 24 | 25 | const response = { 26 | statusCode: 200, 27 | body: JSON.stringify(items) 28 | }; 29 | 30 | // All log statements are written to CloudWatch 31 | console.info(`response from: ${event.path} statusCode: ${response.statusCode} body: ${response.body}`); 32 | return response; 33 | } 34 | -------------------------------------------------------------------------------- /src/handlers/get-by-id.ts: -------------------------------------------------------------------------------- 1 | import 'source-map-support/register'; 2 | import { 3 | APIGatewayProxyEvent, 4 | APIGatewayProxyResult 5 | } from "aws-lambda"; 6 | // Create clients and set shared const values outside of the handler. 7 | import CustomDynamoClient from '../utils/dynamodb'; 8 | 9 | /** 10 | * A simple example includes a HTTP get method to get one item by id from a DynamoDB table. 11 | */ 12 | export const getByIdHandler = async ( 13 | event: APIGatewayProxyEvent, 14 | ): Promise => { 15 | if (event.httpMethod !== 'GET') { 16 | throw new Error(`getMethod only accept GET method, you tried: ${event.httpMethod}`); 17 | } 18 | // All log statements are written to CloudWatch 19 | console.info('received:', event); 20 | 21 | // Get id from pathParameters from APIGateway because of `/{id}` at template.yml 22 | const id = event.pathParameters.id; 23 | 24 | const client = new CustomDynamoClient(); 25 | const item = await client.read(id); 26 | 27 | const response = { 28 | statusCode: 200, 29 | body: JSON.stringify(item) 30 | }; 31 | 32 | // All log statements are written to CloudWatch 33 | console.info(`response from: ${event.path} statusCode: ${response.statusCode} body: ${response.body}`); 34 | return response; 35 | } 36 | -------------------------------------------------------------------------------- /src/handlers/put-item.ts: -------------------------------------------------------------------------------- 1 | import 'source-map-support/register'; 2 | import { 3 | APIGatewayProxyEvent, 4 | APIGatewayProxyResult 5 | } from "aws-lambda"; 6 | 7 | // Create clients and set shared const values outside of the handler. 8 | import CustomSqsClient from '../utils/sqs'; 9 | 10 | /** 11 | * A simple example includes a HTTP post method to add one item to a DynamoDB table. 12 | */ 13 | export const putItemHandler = async ( 14 | event: APIGatewayProxyEvent, 15 | ): Promise => { 16 | if (event.httpMethod !== 'POST') { 17 | throw new Error(`postMethod only accepts POST method, you tried: ${event.httpMethod} method.`); 18 | } 19 | // All log statements are written to CloudWatch 20 | console.info('received:', event); 21 | 22 | // Get id and name from the body of the request 23 | const body = JSON.parse(event.body) 24 | const id = body.id; 25 | const name = body.name; 26 | 27 | const client = new CustomSqsClient(); 28 | const result = await client.send({ id, name }); 29 | 30 | const response = { 31 | statusCode: 201, 32 | body: JSON.stringify({ MessageId: result.MessageId }) 33 | }; 34 | 35 | // All log statements are written to CloudWatch 36 | console.info(`response from: ${event.path} statusCode: ${response.statusCode} body: ${response.body}`); 37 | return response; 38 | } 39 | -------------------------------------------------------------------------------- /src/handlers/write-item.ts: -------------------------------------------------------------------------------- 1 | import 'source-map-support/register'; 2 | import { SQSEvent } from 'aws-lambda'; 3 | 4 | // Create clients and set shared const values outside of the handler. 5 | import CustomDynamoClient from '../utils/dynamodb'; 6 | 7 | /** 8 | * A simple example includes a SQS queue listener to untie HTTP POST API from “heavy” write to DB. 9 | */ 10 | export const writeItemHandler = async ( 11 | event: SQSEvent, 12 | ) => { 13 | console.info('Received from SQS:', event); 14 | 15 | for (const record of event.Records) { 16 | const body = JSON.parse(record.body); 17 | const item = { id: body.id, name: body.name }; 18 | 19 | const client = new CustomDynamoClient(); 20 | await client.write(item); 21 | 22 | console.info('Written to DynamoDB:', item) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/utils/dynamodb.ts: -------------------------------------------------------------------------------- 1 | // Create a DocumentClient that represents the query to add an item 2 | import DynamoDB from 'aws-sdk/clients/dynamodb'; 3 | 4 | // Declare some custom client just to illustrate how TS will include only used files into lambda distribution 5 | export default class CustomDynamoClient { 6 | table: string; 7 | docClient: DynamoDB.DocumentClient; 8 | 9 | constructor(table = process.env.SAMPLE_TABLE) { 10 | this.docClient = new DynamoDB.DocumentClient(); 11 | this.table = table; 12 | } 13 | 14 | async readAll() { 15 | const data = await this.docClient.scan({ TableName: this.table }).promise(); 16 | return data.Items; 17 | } 18 | 19 | async read(id: any) { 20 | var params = { 21 | TableName : this.table, 22 | Key: { id: id }, 23 | }; 24 | const data = await this.docClient.get(params).promise(); 25 | return data.Item; 26 | } 27 | 28 | async write(Item: object) { 29 | const params = { 30 | TableName: this.table, 31 | Item, 32 | }; 33 | 34 | return await this.docClient.put(params).promise(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/utils/sqs.ts: -------------------------------------------------------------------------------- 1 | import SQS from 'aws-sdk/clients/sqs'; 2 | 3 | // Declare some custom client just to illustrate how TS will include only used files into lambda distribution 4 | export default class CustomSqsClient { 5 | queue: string; 6 | sqs: SQS; 7 | 8 | constructor(queue = process.env.ITEM_QUEUE) { 9 | this.sqs = new SQS(); 10 | this.queue = queue; 11 | } 12 | 13 | async send(body: object) { 14 | const sqs = new SQS(); 15 | const params = { 16 | MessageBody: JSON.stringify(body), 17 | QueueUrl: this.queue, 18 | DelaySeconds: 0, 19 | } 20 | return await sqs.sendMessage(params).promise(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /template.yml: -------------------------------------------------------------------------------- 1 | # This is the SAM template that represents the architecture of your serverless application 2 | # https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html 3 | 4 | # The AWSTemplateFormatVersion identifies the capabilities of the template 5 | # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/format-version-structure.html 6 | AWSTemplateFormatVersion: 2010-09-09 7 | Description: >- 8 | aws-sam-typescript-layers-example 9 | 10 | # Transform section specifies one or more macros that AWS CloudFormation uses to process your template 11 | # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html 12 | Transform: 13 | - AWS::Serverless-2016-10-31 14 | 15 | Globals: 16 | Function: 17 | Layers: 18 | - !Ref RuntimeDependenciesLayer 19 | Environment: 20 | Variables: 21 | SAMPLE_TABLE: !Ref SampleTable 22 | ITEM_QUEUE: !Ref WriteQueue 23 | Runtime: nodejs18.x 24 | MemorySize: 128 25 | Timeout: 100 26 | 27 | # Resources declares the AWS resources that you want to include in the stack 28 | # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html 29 | Resources: 30 | # Each Lambda function is defined by properties: 31 | # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction 32 | 33 | # This is a Lambda function config associated with the source code: get-all-items.js 34 | getAllItemsFunction: 35 | Type: AWS::Serverless::Function 36 | Metadata: 37 | BuildMethod: makefile 38 | Properties: 39 | Handler: dist/handlers/get-all-items.getAllItemsHandler 40 | Description: A simple example includes a HTTP get method to get all items from a DynamoDB table. 41 | Policies: 42 | # Give Create/Read/Update/Delete Permissions to the SampleTable 43 | - DynamoDBCrudPolicy: 44 | TableName: !Ref SampleTable 45 | Events: 46 | Api: 47 | Type: Api 48 | Properties: 49 | Path: / 50 | Method: GET 51 | # Each Lambda function is defined by properties: 52 | # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction 53 | 54 | # This is a Lambda function config associated with the source code: get-by-id.js 55 | getByIdFunction: 56 | Type: AWS::Serverless::Function 57 | Metadata: 58 | BuildMethod: makefile 59 | Properties: 60 | Handler: dist/handlers/get-by-id.getByIdHandler 61 | Description: A simple example includes a HTTP get method to get one item by id from a DynamoDB table. 62 | Policies: 63 | # Give Create/Read/Update/Delete Permissions to the SampleTable 64 | - DynamoDBCrudPolicy: 65 | TableName: !Ref SampleTable 66 | Events: 67 | Api: 68 | Type: Api 69 | Properties: 70 | Path: /{id} 71 | Method: GET 72 | # Each Lambda function is defined by properties: 73 | # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction 74 | 75 | # This is a Lambda function config associated with the source code: put-item.js 76 | putItemFunction: 77 | Type: AWS::Serverless::Function 78 | Metadata: 79 | BuildMethod: makefile 80 | Properties: 81 | Handler: dist/handlers/put-item.putItemHandler 82 | Description: A simple example includes a HTTP post method to add one item to an SQS queue (to be written to a DynamoDB table later). 83 | Policies: 84 | # Give permission to send message to an Amazon SQS queue. See https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-template-list.html#sqs-send-message-policy 85 | - SQSSendMessagePolicy: 86 | QueueName: !GetAtt WriteQueue.QueueName 87 | Events: 88 | Api: 89 | Type: Api 90 | Properties: 91 | Path: / 92 | Method: POST 93 | 94 | # This is a Lambda function config associated with the source code: write-item.ts 95 | writeItemFunction: 96 | Type: AWS::Serverless::Function 97 | Metadata: 98 | BuildMethod: makefile 99 | Properties: 100 | Handler: dist/handlers/write-item.writeItemHandler 101 | Description: A simple example includes an SQS subscription to write queued object to DynamoDB 102 | Timeout: 25 # Chosen to be less than the default SQS Visibility Timeout of 30 seconds 103 | Policies: 104 | # Give Create/Read/Update/Delete Permissions to the SampleTable, see https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-template-list.html#dynamo-db-crud-policy 105 | - DynamoDBCrudPolicy: 106 | TableName: !Ref SampleTable 107 | Events: 108 | # Subscription to primary SQS queue 109 | SQSQueueEvent: 110 | Type: SQS 111 | Properties: 112 | Queue: !GetAtt WriteQueue.Arn 113 | BatchSize: 1 114 | 115 | # Simple syntax to create a DynamoDB table with a single attribute primary key, more in 116 | # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlesssimpletable 117 | 118 | # DynamoDB table to store item: {id: <ID>, name: <NAME>} 119 | SampleTable: 120 | Type: AWS::Serverless::SimpleTable 121 | Properties: 122 | PrimaryKey: 123 | Name: id 124 | Type: String 125 | ProvisionedThroughput: 126 | ReadCapacityUnits: 2 127 | WriteCapacityUnits: 2 128 | 129 | WriteQueue: 130 | Type: AWS::SQS::Queue 131 | 132 | RuntimeDependenciesLayer: 133 | Type: AWS::Serverless::LayerVersion 134 | Metadata: 135 | BuildMethod: makefile 136 | Properties: 137 | Description: Runtime dependencies for Lambdas 138 | ContentUri: ./ 139 | CompatibleRuntimes: 140 | - nodejs18.x 141 | RetentionPolicy: Retain 142 | 143 | Outputs: 144 | WebEndpoint: 145 | Description: "API Gateway endpoint URL for Prod stage" 146 | Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/" 147 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "sourceMap": true, 4 | "esModuleInterop": true, 5 | "allowJs": true, 6 | "checkJs": true, 7 | "moduleResolution": "node", 8 | "module": "commonjs", 9 | "lib": ["es2020"], 10 | "target": "es2019", 11 | "outDir": "./dist", 12 | "rootDir": "./src" 13 | }, 14 | "include": ["src/**/*.ts", "src/**/*.js"] 15 | } 16 | --------------------------------------------------------------------------------