diff --git a/code/powertools/typescript/SampleApp/package.json b/code/powertools/typescript/SampleApp/package.json new file mode 100644 index 0000000..935f11d --- /dev/null +++ b/code/powertools/typescript/SampleApp/package.json @@ -0,0 +1,40 @@ +{ + "name": "hello_world", + "version": "1.0.0", + "description": "hello world sample for NodeJS", + "main": "app.js", + "repository": "https://github.com/awslabs/aws-sam-cli/tree/develop/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs", + "author": "SAM CLI", + "license": "MIT", + "scripts": { + "unit": "jest", + "lint": "eslint '*.ts' --quiet --fix", + "compile": "tsc", + "test": "npm run compile && npm run unit" + }, + "dependencies": { + "@aws-lambda-powertools/logger": "^1.13.1", + "@aws-lambda-powertools/metrics": "^1.13.1", + "@aws-lambda-powertools/tracer": "^1.13.1", + "@aws-sdk/lib-dynamodb": "^3.418.0", + "aws-lambda": "^1.0.7", + "aws-sdk": "^2.1489.0", + "esbuild": "^0.19.5", + "tslib": "^2.6.2" + }, + "devDependencies": { + "@types/aws-lambda": "^8.10.92", + "@types/jest": "^29.2.0", + "@types/node": "^18.11.4", + "@typescript-eslint/eslint-plugin": "^5.10.2", + "@typescript-eslint/parser": "^5.10.2", + "eslint": "^8.8.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-prettier": "^4.0.0", + "jest": "^29.2.1", + "prettier": "^2.5.1", + "ts-jest": "^29.0.5", + "ts-node": "^10.9.1", + "typescript": "^4.8.4" + } +} diff --git a/code/powertools/typescript/SampleApp/src/functions/get-by-id/app.ts b/code/powertools/typescript/SampleApp/src/functions/get-by-id/app.ts new file mode 100644 index 0000000..62abcce --- /dev/null +++ b/code/powertools/typescript/SampleApp/src/functions/get-by-id/app.ts @@ -0,0 +1,58 @@ +import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda'; +import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"; +import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // ES6 import + +const client = new DynamoDBClient({}); +const ddbDocClient = DynamoDBDocument.from(client); + + +export const lambdaHandler = async (event: APIGatewayProxyEvent, context: Context): Promise => { + + + let id; + let response: APIGatewayProxyResult; + + id = event.pathParameters.id; + const item = await getItemById(id); + + + try { + + const items = await getItemById(id); + response = { + statusCode: 200, + headers: { + 'Access-Control-Allow-Origin': '*' + }, + body: JSON.stringify(items) + } + } catch (err) { + let error_message = `Error getting dynamodb item ${id}: ${err}` + + response = { + statusCode: 500, + body: JSON.stringify({ + message: error_message, + }), + }; + } finally { + + } + + return response; +}; + +const getItemById = async (id) => { + let response + try { + var params = { + TableName: process.env.SAMPLE_TABLE, + Key: { id: id } + } + + response = await ddbDocClient.get(params); + } catch (err) { + throw err + } + return response + } diff --git a/code/powertools/typescript/SampleApp/src/functions/get-items/app.ts b/code/powertools/typescript/SampleApp/src/functions/get-items/app.ts new file mode 100644 index 0000000..fd2f409 --- /dev/null +++ b/code/powertools/typescript/SampleApp/src/functions/get-items/app.ts @@ -0,0 +1,53 @@ +import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; +import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"; +import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // ES6 import + +const client = new DynamoDBClient({}); +const ddbDocClient = DynamoDBDocument.from(client); + + +export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise => { + + + let response: APIGatewayProxyResult; + + + try { + + + const items = await getAllItems(); + response = { + statusCode: 200, + headers: { + 'Access-Control-Allow-Origin': '*' + }, + body: JSON.stringify(items) + } + } catch (err) { + let error_message = `Error getting dynamodb items: ${err}` + + response = { + statusCode: 500, + body: JSON.stringify({ + message: error_message, + }), + }; + } finally { + + } + + return response; +}; + +const getAllItems = async () => { + let response + try { + var params = { + TableName: process.env.SAMPLE_TABLE, + } + response = await ddbDocClient.scan(params); + } catch (err) { + throw err + } + return response +} diff --git a/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts b/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts new file mode 100644 index 0000000..22b6a47 --- /dev/null +++ b/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts @@ -0,0 +1,59 @@ +import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; +import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"; +import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // ES6 import + +const client = new DynamoDBClient({}); +const ddbDocClient = DynamoDBDocument.from(client); + + +export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise => { + + let response: APIGatewayProxyResult; + + try { + + + const item = await putItem(event) + + response = { + statusCode: 200, + headers: { + 'Access-Control-Allow-Origin': '*' + }, + body: "Item adicionado com sucesso" + } + } catch (err) { + let error_message = `Error getting dynamodb items: ${err}` + + response = { + statusCode: 500, + body: JSON.stringify({ + message: error_message, + }), + }; + } finally { + + } + + return response; +}; + +const putItem = async (event) => { + let response + try { + const body = JSON.parse(event.body) + const id = body.Id.toString() + const name = body.Name + + var params = { + TableName: process.env.SAMPLE_TABLE, + Item: { id: id, name: name } + } + + response = await ddbDocClient.put(params) + + } catch (err) { + throw err + } + return response +} diff --git a/code/powertools/typescript/SampleApp/template.yaml b/code/powertools/typescript/SampleApp/template.yaml new file mode 100644 index 0000000..3764204 --- /dev/null +++ b/code/powertools/typescript/SampleApp/template.yaml @@ -0,0 +1,142 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + SampleApp + + Sample SAM Template for SampleApp + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Runtime: nodejs18.x + Timeout: 15 + Tracing: Active + MemorySize: 128 + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: powertools-typescript-sample-app + LOG_LEVEL: debug + APP_NAME: !Ref SampleTable + SAMPLE_TABLE: !Ref SampleTable + SERVICE_NAME: item_service + ENABLE_DEBUG: false + AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1 # Enable usage of KeepAlive to reduce overhead of short-lived actions, like DynamoDB queries + Api: + TracingEnabled: true + +Resources: + Api: + Type: AWS::Serverless::Api + Properties: + StageName: Prod + + getAllItemsFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: src/functions/get-items/ + Handler: app.lambdaHandler + Runtime: nodejs18.x + Architectures: + - x86_64 + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref SampleTable + - CloudWatchPutMetricPolicy: {} + - CloudWatchLambdaInsightsExecutionRolePolicy + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + RestApiId: !Ref Api + Path: /items + Method: get + Metadata: # Manage esbuild properties + BuildMethod: esbuild + BuildProperties: + Minify: true + Target: "es2020" + Sourcemap: false + EntryPoints: + - app.ts + + getByIdFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: src/functions/get-by-id/ + Handler: app.lambdaHandler + Runtime: nodejs18.x + Architectures: + - x86_64 + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref SampleTable + - CloudWatchPutMetricPolicy: {} + - CloudWatchLambdaInsightsExecutionRolePolicy + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + RestApiId: !Ref Api + Path: /items/{id} + Method: get + Metadata: # Manage esbuild properties + BuildMethod: esbuild + BuildProperties: + Minify: true + Target: "es2020" + Sourcemap: false + EntryPoints: + - app.ts + + putItemFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: src/functions/put-item/ + Handler: app.lambdaHandler + Runtime: nodejs18.x + Architectures: + - x86_64 + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref SampleTable + - CloudWatchPutMetricPolicy: {} + - CloudWatchLambdaInsightsExecutionRolePolicy + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + RestApiId: !Ref Api + Path: /items + Method: post + Metadata: # Manage esbuild properties + BuildMethod: esbuild + BuildProperties: + Minify: true + Target: "es2020" + Sourcemap: false + EntryPoints: + - app.ts + + # DynamoDB Table + SampleTable: + Type: AWS::Serverless::SimpleTable + Properties: + ProvisionedThroughput: + ReadCapacityUnits: 10 + WriteCapacityUnits: 5 + TableName: SampleAppItem + PrimaryKey: + Name: id + Type: String + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + ApiUrl: + Description: "API Gateway endpoint URL for Prod stage" + Value: !Sub "https://${Api}.execute-api.${AWS::Region}.amazonaws.com/Prod/" + + SampleTable: + Value: !GetAtt SampleTable.Arn + Description: Sample Data Table ARN diff --git a/code/powertools/typescript/SampleSolution/.aws-sam/build.toml b/code/powertools/typescript/SampleSolution/.aws-sam/build.toml new file mode 100644 index 0000000..78d26f5 --- /dev/null +++ b/code/powertools/typescript/SampleSolution/.aws-sam/build.toml @@ -0,0 +1,61 @@ +# This file is auto generated by SAM CLI build command + +[function_build_definitions] +[function_build_definitions.180149cd-fdeb-4b69-8092-3aa482b8dd2e] +codeuri = "/Users/rsperes/Documents/workshop/serverless-observability-workshop/code/powertools/typescript/SampleSolution/src/functions/get-items" +runtime = "nodejs18.x" +architecture = "x86_64" +handler = "app.lambdaHandler" +manifest_hash = "" +packagetype = "Zip" +functions = ["getAllItemsFunction"] + +[function_build_definitions.180149cd-fdeb-4b69-8092-3aa482b8dd2e.metadata] +BuildMethod = "esbuild" + +[function_build_definitions.180149cd-fdeb-4b69-8092-3aa482b8dd2e.metadata.BuildProperties] +Minify = true +Target = "es2020" +Sourcemap = false +EntryPoints = ["app.ts"] + + +[function_build_definitions.4a585729-456f-4c34-955d-6fd829b4fc6d] +codeuri = "/Users/rsperes/Documents/workshop/serverless-observability-workshop/code/powertools/typescript/SampleSolution/src/functions/get-by-id" +runtime = "nodejs18.x" +architecture = "x86_64" +handler = "app.lambdaHandler" +manifest_hash = "" +packagetype = "Zip" +functions = ["getByIdFunction"] + +[function_build_definitions.4a585729-456f-4c34-955d-6fd829b4fc6d.metadata] +BuildMethod = "esbuild" + +[function_build_definitions.4a585729-456f-4c34-955d-6fd829b4fc6d.metadata.BuildProperties] +Minify = true +Target = "es2020" +Sourcemap = false +EntryPoints = ["app.ts"] + + +[function_build_definitions.7c03eef8-6f3f-4e44-96f7-752ddf1f0ecf] +codeuri = "/Users/rsperes/Documents/workshop/serverless-observability-workshop/code/powertools/typescript/SampleSolution/src/functions/put-item" +runtime = "nodejs18.x" +architecture = "x86_64" +handler = "app.lambdaHandler" +manifest_hash = "" +packagetype = "Zip" +functions = ["putItemFunction"] + +[function_build_definitions.7c03eef8-6f3f-4e44-96f7-752ddf1f0ecf.metadata] +BuildMethod = "esbuild" + +[function_build_definitions.7c03eef8-6f3f-4e44-96f7-752ddf1f0ecf.metadata.BuildProperties] +Minify = true +Target = "es2020" +Sourcemap = false +EntryPoints = ["app.ts"] + + +[layer_build_definitions] diff --git a/code/powertools/typescript/SampleSolution/README.md b/code/powertools/typescript/SampleSolution/README.md new file mode 100644 index 0000000..7525aae --- /dev/null +++ b/code/powertools/typescript/SampleSolution/README.md @@ -0,0 +1,127 @@ +# basicapp + +This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders. + +- hello-world - Code for the application's Lambda function written in TypeScript. +- events - Invocation events that you can use to invoke the function. +- hello-world/tests - Unit tests for the application code. +- template.yaml - A template that defines the application's AWS resources. + +The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. + +If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. +The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started. + +* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) +* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) + +## Deploy the sample application + +The Serverless Application Model Command Line Interface (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. + +To use the SAM CLI, you need the following tools. + +* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +* Node.js - [Install Node.js 18](https://nodejs.org/en/), including the NPM package management tool. +* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) + +To build and deploy your application for the first time, run the following in your shell: + +```bash +sam build +sam deploy --guided +``` + +The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts: + +* **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. +* **AWS Region**: The AWS region you want to deploy your app to. +* **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. +* **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 modifies 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. +* **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. + +You can find your API Gateway Endpoint URL in the output values displayed after deployment. + +## Use the SAM CLI to build and test locally + +Build your application with the `sam build` command. + +```bash +basicapp$ sam build +``` + +The SAM CLI installs dependencies defined in `hello-world/package.json`, compiles TypeScript with esbuild, creates a deployment package, and saves it in the `.aws-sam/build` folder. + +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. + +Run functions locally and invoke them with the `sam local invoke` command. + +```bash +basicapp$ sam local invoke HelloWorldFunction --event events/event.json +``` + +The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. + +```bash +basicapp$ sam local start-api +basicapp$ curl http://localhost:3000/ +``` + +The 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. + +```yaml + Events: + HelloWorld: + Type: Api + Properties: + Path: /hello + Method: get +``` + +## Add a resource to your application +The application template uses AWS Serverless Application Model (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 not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. + +## Fetch, tail, and filter Lambda function logs + +To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed 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. + +`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. + +```bash +basicapp$ sam logs -n HelloWorldFunction --stack-name basicapp --tail +``` + +You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). + +## Unit tests + +Tests are defined in the `hello-world/tests` folder in this project. Use NPM to install the [Jest test framework](https://jestjs.io/) and run unit tests. + +```bash +basicapp$ cd hello-world +hello-world$ npm install +hello-world$ npm run test +``` + +## Cleanup + +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: + +```bash +sam delete --stack-name basicapp +``` + +## Resources + +See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. + +Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/code/powertools/typescript/SampleSolution/events/event.json b/code/powertools/typescript/SampleSolution/events/event.json new file mode 100644 index 0000000..070ad8e --- /dev/null +++ b/code/powertools/typescript/SampleSolution/events/event.json @@ -0,0 +1,62 @@ +{ + "body": "{\"message\": \"hello world\"}", + "resource": "/{proxy+}", + "path": "/path/to/resource", + "httpMethod": "POST", + "isBase64Encoded": false, + "queryStringParameters": { + "foo": "bar" + }, + "pathParameters": { + "proxy": "/path/to/resource" + }, + "stageVariables": { + "baz": "qux" + }, + "headers": { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate, sdch", + "Accept-Language": "en-US,en;q=0.8", + "Cache-Control": "max-age=0", + "CloudFront-Forwarded-Proto": "https", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-Mobile-Viewer": "false", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Tablet-Viewer": "false", + "CloudFront-Viewer-Country": "US", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Custom User Agent String", + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "X-Forwarded-Port": "443", + "X-Forwarded-Proto": "https" + }, + "requestContext": { + "accountId": "123456789012", + "resourceId": "123456", + "stage": "prod", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "requestTime": "09/Apr/2015:12:34:56 +0000", + "requestTimeEpoch": 1428582896000, + "identity": { + "cognitoIdentityPoolId": null, + "accountId": null, + "cognitoIdentityId": null, + "caller": null, + "accessKey": null, + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": null, + "userAgent": "Custom User Agent String", + "user": null + }, + "path": "/prod/path/to/resource", + "resourcePath": "/{proxy+}", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } +} diff --git a/code/powertools/typescript/SampleSolution/package.json b/code/powertools/typescript/SampleSolution/package.json new file mode 100644 index 0000000..935f11d --- /dev/null +++ b/code/powertools/typescript/SampleSolution/package.json @@ -0,0 +1,40 @@ +{ + "name": "hello_world", + "version": "1.0.0", + "description": "hello world sample for NodeJS", + "main": "app.js", + "repository": "https://github.com/awslabs/aws-sam-cli/tree/develop/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs", + "author": "SAM CLI", + "license": "MIT", + "scripts": { + "unit": "jest", + "lint": "eslint '*.ts' --quiet --fix", + "compile": "tsc", + "test": "npm run compile && npm run unit" + }, + "dependencies": { + "@aws-lambda-powertools/logger": "^1.13.1", + "@aws-lambda-powertools/metrics": "^1.13.1", + "@aws-lambda-powertools/tracer": "^1.13.1", + "@aws-sdk/lib-dynamodb": "^3.418.0", + "aws-lambda": "^1.0.7", + "aws-sdk": "^2.1489.0", + "esbuild": "^0.19.5", + "tslib": "^2.6.2" + }, + "devDependencies": { + "@types/aws-lambda": "^8.10.92", + "@types/jest": "^29.2.0", + "@types/node": "^18.11.4", + "@typescript-eslint/eslint-plugin": "^5.10.2", + "@typescript-eslint/parser": "^5.10.2", + "eslint": "^8.8.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-prettier": "^4.0.0", + "jest": "^29.2.1", + "prettier": "^2.5.1", + "ts-jest": "^29.0.5", + "ts-node": "^10.9.1", + "typescript": "^4.8.4" + } +} diff --git a/code/powertools/typescript/SampleSolution/src/functions/get-by-id/app.ts b/code/powertools/typescript/SampleSolution/src/functions/get-by-id/app.ts new file mode 100644 index 0000000..23d4802 --- /dev/null +++ b/code/powertools/typescript/SampleSolution/src/functions/get-by-id/app.ts @@ -0,0 +1,66 @@ +import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda'; +import { Logger } from '@aws-lambda-powertools/logger'; +import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"; +import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // ES6 import + +const client = new DynamoDBClient({}); +const ddbDocClient = DynamoDBDocument.from(client); + +const logger = new Logger(); + + +export const lambdaHandler = async (event: APIGatewayProxyEvent, context: Context): Promise => { + + let id; + let response: APIGatewayProxyResult; + + id = event.pathParameters.id; + const item = await getItemById(id); + + let location = event.requestContext.identity.sourceIp + // you can copy and paste this line anywhere in the code to create a log line + logger.info("Getting ip address from external service"); + logger.info("Location: " + location); + + + try { + + const items = await getItemById(id); + response = { + statusCode: 200, + headers: { + 'Access-Control-Allow-Origin': '*' + }, + body: JSON.stringify(items) + } + } catch (err) { + let error_message = `Error getting dynamodb item ${id}: ${err}` + // error log + logger.error(error_message); + response = { + statusCode: 500, + body: JSON.stringify({ + message: error_message, + }), + }; + } finally { + + } + + return response; +}; + +const getItemById = async (id) => { + let response + try { + var params = { + TableName: process.env.SAMPLE_TABLE, + Key: { id: id } + } + + response = await ddbDocClient.get(params); + } catch (err) { + throw err + } + return response + } \ No newline at end of file diff --git a/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts b/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts new file mode 100644 index 0000000..8422b60 --- /dev/null +++ b/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts @@ -0,0 +1,74 @@ +import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; +import { Logger } from '@aws-lambda-powertools/logger'; +import { Tracer } from '@aws-lambda-powertools/tracer'; +import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"; +import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // ES6 import + +const client = new DynamoDBClient({}); +const ddbDocClient = DynamoDBDocument.from(client); + +const logger = new Logger(); +const tracer = new Tracer(); + +export const lambdaHandler = async (event: APIGatewayProxyEvent ): Promise => { + + let response: APIGatewayProxyResult; + + let location = event.requestContext.identity.sourceIp + // you can copy and paste this line anywhere in the code to create a log line + logger.info("Getting ip address from external service"); + logger.info("Location: " + location); + + tracer.putAnnotation("Location", location); + tracer.putMetadata('Location', location); + + + // You need to take the segment automatically created by Lambda and pass it to Tracer + const segment = tracer.getSegment(); + let subsegment; + //create a subsegment with name GetCAllingIP + subsegment = segment.addNewSubsegment('GetCallingIP'); + tracer.setSegment(subsegment); + //add the IP as a metadata to the newly created subsegment + tracer.putMetadata('Location', location); + + + try { + const items = await getAllItems(); + response = { + statusCode: 200, + headers: { + 'Access-Control-Allow-Origin': '*' + }, + body: JSON.stringify(items) + } + } catch (err) { + let error_message = `Error getting dynamodb items: ${err}` + // error log + logger.error(error_message); + response = { + statusCode: 500, + body: JSON.stringify({ + message: error_message, + }), + }; + } finally { + subsegment.close(); + tracer.setSegment(segment); + } + + return response; +}; + +const getAllItems = async () => { + let response + try { + var params = { + TableName: process.env.SAMPLE_TABLE, + } + response = await ddbDocClient.scan(params); + } catch (err) { + throw err + } + return response +} diff --git a/code/powertools/typescript/SampleSolution/src/functions/put-item/app.ts b/code/powertools/typescript/SampleSolution/src/functions/put-item/app.ts new file mode 100644 index 0000000..f5338d2 --- /dev/null +++ b/code/powertools/typescript/SampleSolution/src/functions/put-item/app.ts @@ -0,0 +1,107 @@ +import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; +import { Logger } from '@aws-lambda-powertools/logger'; +import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics'; +import { Tracer } from '@aws-lambda-powertools/tracer'; +import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"; +import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // ES6 import + +const client = new DynamoDBClient({}); +const ddbDocClient = DynamoDBDocument.from(client); + +const logger = new Logger(); +const metrics = new Metrics({ + namespace: 'SampleApp', + serviceName: 'Items', +}); +const tracer = new Tracer(); + +export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise => { + + + let response: APIGatewayProxyResult; + + const singleMetric = metrics.singleMetric(); + // This metric will have the "FunctionContext" dimension, and no "metricUnit" dimension: + singleMetric.addDimension('FunctionContext', '$LATEST'); + singleMetric.addMetric('TotalExecutions', MetricUnits.Count, 1); + + // you can copy and paste this line anywhere in the code to create a log line + let location = event.requestContext.identity.sourceIp; + let body = JSON.parse(event.body) + + logger.appendKeys({ + AdditionalInfo: { + RequestLocation: location, + ItemID: body.id, + } + }); + + logger.debug("ip address successfuly captured"); //this log entry will have additional info + + // ColdStart is an automatic metric that Lambda Powertools creates, you can create more metrics + metrics.captureColdStartMetric(); + + + // You need to take the segment automatically created by Lambda and pass it to Tracer + const segment = tracer.getSegment(); + const handlerSegment = segment.addNewSubsegment(`## ${process.env._HANDLER}`); + + + try { + + tracer.setSegment(handlerSegment); + + const item = await putItem(event) + + metrics.addMetric("SuccessfulPutItem", MetricUnits.Count, 1); + metrics.addMetadata("request_location", location); + + response = { + statusCode: 200, + headers: { + 'Access-Control-Allow-Origin': '*' + }, + body: "Item added successfuly" + } + + } catch (err) { + let error_message = `Error getting dynamodb items: ${err}` + // error log + logger.error(error_message); + metrics.addMetric("FailedPutItem", MetricUnits.Count, 1); + response = { + statusCode: 500, + body: JSON.stringify({ + message: error_message, + }), + }; + } finally { + // Close subsegments (the AWS Lambda one is closed automatically) + handlerSegment.close(); // (## index.handler) + + // This line forces metrics to be sent to cloudwatch to process via EMF - Do not remove!! + metrics.publishStoredMetrics(); + } + + return response; +}; + +const putItem = async (event) => { + let response + try { + const body = JSON.parse(event.body) + const id = body.Id.toString() + const name = body.Name + + var params = { + TableName: process.env.SAMPLE_TABLE, + Item: { id: id, name: name } + } + + response = await ddbDocClient.put(params) + + } catch (err) { + throw err + } + return response +} diff --git a/code/powertools/typescript/SampleSolution/template.yaml b/code/powertools/typescript/SampleSolution/template.yaml new file mode 100644 index 0000000..14bd13d --- /dev/null +++ b/code/powertools/typescript/SampleSolution/template.yaml @@ -0,0 +1,142 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + SampleApp + + Sample SAM Template for SampleApp + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Runtime: nodejs18.x + Timeout: 15 + Tracing: Active + MemorySize: 128 + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: powertools-typescript-sample-app + LOG_LEVEL: debug + APP_NAME: !Ref SampleTable + SAMPLE_TABLE: !Ref SampleTable + SERVICE_NAME: item_service + ENABLE_DEBUG: false + AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1 # Enable usage of KeepAlive to reduce overhead of short-lived actions, like DynamoDB queries + Api: + TracingEnabled: true + +Resources: + Api: + Type: AWS::Serverless::Api + Properties: + StageName: Prod + + getAllItemsFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: src/functions/get-items/ + Handler: app.lambdaHandler + Runtime: nodejs18.x + Architectures: + - x86_64 + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref SampleTable + - CloudWatchPutMetricPolicy: {} + - CloudWatchLambdaInsightsExecutionRolePolicy + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + RestApiId: !Ref Api + Path: /items + Method: GET + Metadata: # Manage esbuild properties + BuildMethod: esbuild + BuildProperties: + Minify: true + Target: "es2020" + Sourcemap: false + EntryPoints: + - app.ts + + getByIdFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: src/functions/get-by-id/ + Handler: app.lambdaHandler + Runtime: nodejs18.x + Architectures: + - x86_64 + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref SampleTable + - CloudWatchPutMetricPolicy: {} + - CloudWatchLambdaInsightsExecutionRolePolicy + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + RestApiId: !Ref Api + Path: /items/{id} + Method: GET + Metadata: # Manage esbuild properties + BuildMethod: esbuild + BuildProperties: + Minify: true + Target: "es2020" + Sourcemap: false + EntryPoints: + - app.ts + + putItemFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: src/functions/put-item/ + Handler: app.lambdaHandler + Runtime: nodejs18.x + Architectures: + - x86_64 + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref SampleTable + - CloudWatchPutMetricPolicy: {} + - CloudWatchLambdaInsightsExecutionRolePolicy + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + RestApiId: !Ref Api + Path: /items + Method: POST + Metadata: # Manage esbuild properties + BuildMethod: esbuild + BuildProperties: + Minify: true + Target: "es2020" + Sourcemap: false + EntryPoints: + - app.ts + + # DynamoDB Table + SampleTable: + Type: AWS::Serverless::SimpleTable + Properties: + ProvisionedThroughput: + ReadCapacityUnits: 10 + WriteCapacityUnits: 5 + TableName: SampleAppItem + PrimaryKey: + Name: id + Type: String + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + ApiUrl: + Description: "API Gateway endpoint URL for Prod stage" + Value: !Sub "https://${Api}.execute-api.${AWS::Region}.amazonaws.com/Prod/" + + SampleTable: + Value: !GetAtt SampleTable.Arn + Description: Sample Data Table ARN