From 36405376071a0fa5afa8d7a9c2f98736a1f47213 Mon Sep 17 00:00:00 2001 From: Rodrigo Peres Date: Tue, 10 Oct 2023 16:16:15 -0300 Subject: [PATCH 1/4] Final typescript version --- .../typescript/SampleApp/package.json | 40 +++++ .../SampleApp/src/functions/get-by-id/app.ts | 58 +++++++ .../SampleApp/src/functions/get-items/app.ts | 53 +++++++ .../SampleApp/src/functions/put-item/app.ts | 59 ++++++++ .../typescript/SampleApp/template.yaml | 142 ++++++++++++++++++ .../typescript/SampleSolution/README.md | 127 ++++++++++++++++ .../SampleSolution/events/event.json | 62 ++++++++ .../typescript/SampleSolution/package.json | 40 +++++ .../src/functions/get-by-id/app.ts | 94 ++++++++++++ .../src/functions/get-items/app.ts | 89 +++++++++++ .../src/functions/put-item/app.ts | 97 ++++++++++++ .../typescript/SampleSolution/template.yaml | 142 ++++++++++++++++++ 12 files changed, 1003 insertions(+) create mode 100644 code/powertools/typescript/SampleApp/package.json create mode 100644 code/powertools/typescript/SampleApp/src/functions/get-by-id/app.ts create mode 100644 code/powertools/typescript/SampleApp/src/functions/get-items/app.ts create mode 100644 code/powertools/typescript/SampleApp/src/functions/put-item/app.ts create mode 100644 code/powertools/typescript/SampleApp/template.yaml create mode 100644 code/powertools/typescript/SampleSolution/README.md create mode 100644 code/powertools/typescript/SampleSolution/events/event.json create mode 100644 code/powertools/typescript/SampleSolution/package.json create mode 100644 code/powertools/typescript/SampleSolution/src/functions/get-by-id/app.ts create mode 100644 code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts create mode 100644 code/powertools/typescript/SampleSolution/src/functions/put-item/app.ts create mode 100644 code/powertools/typescript/SampleSolution/template.yaml diff --git a/code/powertools/typescript/SampleApp/package.json b/code/powertools/typescript/SampleApp/package.json new file mode 100644 index 0000000..de467b8 --- /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": "^3.420.0", + "esbuild": "^0.14.14", + "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..89e209e --- /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({ region: "us-east-1" }); +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..0f68224 --- /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({ region: "us-east-1" }); +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..8e08ddb --- /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({ region: "us-east-1" }); +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 + 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/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..de467b8 --- /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": "^3.420.0", + "esbuild": "^0.14.14", + "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..e498843 --- /dev/null +++ b/code/powertools/typescript/SampleSolution/src/functions/get-by-id/app.ts @@ -0,0 +1,94 @@ +import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } 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({ region: "us-east-1" }); +const ddbDocClient = DynamoDBDocument.from(client); + +const logger = new Logger(); +const metrics = new Metrics(); +const tracer = new Tracer(); + +export const lambdaHandler = async (event: APIGatewayProxyEvent, context: Context): Promise => { + /* This SampleAPP contains + 1 - Running logs + 2 - Working metrics + 3 - Working Tracer + 4 - Running DynamoDB search by item + 5 - You can create more segments and subsegments for Tracer + 6 - You can customize other items you want, such as the type of event and things like that + */ + + let id; + let response: APIGatewayProxyResult; + + id = event.pathParameters.id; + const item = await getItemById(id); + + // you can copy and paste this line anywhere in the code to create a log line + logger.info("Create a log line"); + logger.info("Event received: " + JSON.stringify(event, null, 2)); + + + // ColdStart is an automatic metric that Lambda Powertools creates, you can create more metrics + metrics.captureColdStartMetric(); + + // This line creates metrics, put the metric you want in the part of the code you want + // MetricsUnits is the type of metric, it can be Count, Bytes, Milliseconds, None, Percent, etc. + metrics.addMetric("FirstMetric", MetricUnits.Count, 1); + + + // 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 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 { + // 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 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/SampleSolution/src/functions/get-items/app.ts b/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts new file mode 100644 index 0000000..e8080b7 --- /dev/null +++ b/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts @@ -0,0 +1,89 @@ +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({ region: "us-east-1" }); +const ddbDocClient = DynamoDBDocument.from(client); + +const logger = new Logger(); +const metrics = new Metrics(); +const tracer = new Tracer(); + +export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise => { + /* This SampleAPP contains + 1 - Running logs + 2 - Working metrics + 3 - Working Tracer + 4 - Running DynamoDB search by item + 5 - You can create more segments and subsegments for Tracer + 6 - You can customize other items you want, such as the type of event and things like that + */ + + let response: APIGatewayProxyResult; + + // you can copy and paste this line anywhere in the code to create a log line + logger.info("Create a log line"); + logger.info("Event received: " + JSON.stringify(event, null, 2)); + + + // ColdStart is an automatic metric that Lambda Powertools creates, you can create more metrics + metrics.captureColdStartMetric(); + + // This line creates metrics, put the metric you want in the part of the code you want + // MetricsUnits is the type of metric, it can be Count, Bytes, Milliseconds, None, Percent, etc. + metrics.addMetric("FirstMetric", MetricUnits.Count, 1); + + + // 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 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 { + // 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 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..c884ef8 --- /dev/null +++ b/code/powertools/typescript/SampleSolution/src/functions/put-item/app.ts @@ -0,0 +1,97 @@ +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({ region: "us-east-1" }); +const ddbDocClient = DynamoDBDocument.from(client); + +const logger = new Logger(); +const metrics = new Metrics(); +const tracer = new Tracer(); + +export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise => { + /* This SampleAPP contains + 1 - Running logs + 2 - Working metrics + 3 - Working Tracer + 4 - Running DynamoDB search by item + 5 - You can create more segments and subsegments for Tracer + 6 - You can customize other items you want, such as the type of event and things like that + */ + + let response: APIGatewayProxyResult; + + // you can copy and paste this line anywhere in the code to create a log line + logger.info("Create a log line"); + logger.info("Event received: " + JSON.stringify(event, null, 2)); + + + // ColdStart is an automatic metric that Lambda Powertools creates, you can create more metrics + metrics.captureColdStartMetric(); + + // This line creates metrics, put the metric you want in the part of the code you want + // MetricsUnits is the type of metric, it can be Count, Bytes, Milliseconds, None, Percent, etc. + metrics.addMetric("FirstMetric", MetricUnits.Count, 1); + + + // 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) + + response = { + statusCode: 200, + headers: { + 'Access-Control-Allow-Origin': '*' + }, + body: "Item adicionado com sucesso" + } + } 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 { + // 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 + 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..3764204 --- /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 From bb7a5d90c896a1280e4f549b3e55d6485b28bfa1 Mon Sep 17 00:00:00 2001 From: Rodrigo Peres Date: Mon, 23 Oct 2023 15:09:12 -0300 Subject: [PATCH 2/4] Refactor to match netcore modifications --- .../SampleSolution/.aws-sam/build.toml | 61 +++++++++++++++++++ .../typescript/SampleSolution/package.json | 2 +- .../src/functions/get-by-id/app.ts | 38 ++---------- .../src/functions/get-items/app.ts | 51 ++++++---------- .../src/functions/put-item/app.ts | 44 +++++++------ .../typescript/SampleSolution/template.yaml | 12 ++-- 6 files changed, 118 insertions(+), 90 deletions(-) create mode 100644 code/powertools/typescript/SampleSolution/.aws-sam/build.toml 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/package.json b/code/powertools/typescript/SampleSolution/package.json index de467b8..8b374ae 100644 --- a/code/powertools/typescript/SampleSolution/package.json +++ b/code/powertools/typescript/SampleSolution/package.json @@ -18,7 +18,7 @@ "@aws-lambda-powertools/tracer": "^1.13.1", "@aws-sdk/lib-dynamodb": "^3.418.0", "aws-lambda": "^1.0.7", - "aws-sdk": "^3.420.0", + "aws-sdk": "^2.1463.0", "esbuild": "^0.14.14", "tslib": "^2.6.2" }, 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 index e498843..4c86448 100644 --- a/code/powertools/typescript/SampleSolution/src/functions/get-by-id/app.ts +++ b/code/powertools/typescript/SampleSolution/src/functions/get-by-id/app.ts @@ -1,7 +1,5 @@ import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } 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 @@ -9,18 +7,9 @@ const client = new DynamoDBClient({ region: "us-east-1" }); const ddbDocClient = DynamoDBDocument.from(client); const logger = new Logger(); -const metrics = new Metrics(); -const tracer = new Tracer(); + export const lambdaHandler = async (event: APIGatewayProxyEvent, context: Context): Promise => { - /* This SampleAPP contains - 1 - Running logs - 2 - Working metrics - 3 - Working Tracer - 4 - Running DynamoDB search by item - 5 - You can create more segments and subsegments for Tracer - 6 - You can customize other items you want, such as the type of event and things like that - */ let id; let response: APIGatewayProxyResult; @@ -28,26 +17,13 @@ export const lambdaHandler = async (event: APIGatewayProxyEvent, context: Contex 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("Create a log line"); - logger.info("Event received: " + JSON.stringify(event, null, 2)); - - - // ColdStart is an automatic metric that Lambda Powertools creates, you can create more metrics - metrics.captureColdStartMetric(); - - // This line creates metrics, put the metric you want in the part of the code you want - // MetricsUnits is the type of metric, it can be Count, Bytes, Milliseconds, None, Percent, etc. - metrics.addMetric("FirstMetric", MetricUnits.Count, 1); - + logger.info("Getting ip address from external service"); + logger.info("Location: " + location); - // 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 items = await getItemById(id); response = { @@ -68,11 +44,7 @@ export const lambdaHandler = async (event: APIGatewayProxyEvent, context: Contex }), }; } 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; @@ -91,4 +63,4 @@ const getItemById = async (id) => { 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 index e8080b7..b805043 100644 --- a/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts +++ b/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts @@ -1,6 +1,5 @@ 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 @@ -9,43 +8,32 @@ const client = new DynamoDBClient({ region: "us-east-1" }); const ddbDocClient = DynamoDBDocument.from(client); const logger = new Logger(); -const metrics = new Metrics(); const tracer = new Tracer(); -export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise => { - /* This SampleAPP contains - 1 - Running logs - 2 - Working metrics - 3 - Working Tracer - 4 - Running DynamoDB search by item - 5 - You can create more segments and subsegments for Tracer - 6 - You can customize other items you want, such as the type of event and things like that - */ +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("Create a log line"); - logger.info("Event received: " + JSON.stringify(event, null, 2)); - - - // ColdStart is an automatic metric that Lambda Powertools creates, you can create more metrics - metrics.captureColdStartMetric(); - - // This line creates metrics, put the metric you want in the part of the code you want - // MetricsUnits is the type of metric, it can be Count, Bytes, Milliseconds, None, Percent, etc. - metrics.addMetric("FirstMetric", MetricUnits.Count, 1); - - + 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(); - const handlerSegment = segment.addNewSubsegment(`## ${process.env._HANDLER}`); + 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 { - - tracer.setSegment(handlerSegment); - const items = await getAllItems(); response = { statusCode: 200, @@ -65,11 +53,8 @@ export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise => { - /* This SampleAPP contains - 1 - Running logs - 2 - Working metrics - 3 - Working Tracer - 4 - Running DynamoDB search by item - 5 - You can create more segments and subsegments for Tracer - 6 - You can customize other items you want, such as the type of event and things like that - */ + 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 - logger.info("Create a log line"); - logger.info("Event received: " + JSON.stringify(event, null, 2)); - + 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(); - // This line creates metrics, put the metric you want in the part of the code you want - // MetricsUnits is the type of metric, it can be Count, Bytes, Milliseconds, None, Percent, etc. - metrics.addMetric("FirstMetric", MetricUnits.Count, 1); - // You need to take the segment automatically created by Lambda and pass it to Tracer const segment = tracer.getSegment(); @@ -47,18 +52,23 @@ export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise Date: Fri, 27 Oct 2023 11:59:49 -0300 Subject: [PATCH 3/4] Added casting to id --- .../typescript/SampleApp/src/functions/put-item/app.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts b/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts index 8e08ddb..67b73e9 100644 --- a/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts +++ b/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts @@ -42,7 +42,7 @@ const putItem = async (event) => { let response try { const body = JSON.parse(event.body) - const id = body.id + const id = body.id.toString() const name = body.name var params = { From 5e391c10e00d2168a7a4d5445e9863c6ee888cbc Mon Sep 17 00:00:00 2001 From: Rodrigo Peres Date: Mon, 6 Nov 2023 19:02:14 -0300 Subject: [PATCH 4/4] Code v2. Corrected captalization bug, template.yaml. package.json --- code/powertools/typescript/SampleApp/package.json | 4 ++-- .../typescript/SampleApp/src/functions/get-by-id/app.ts | 2 +- .../typescript/SampleApp/src/functions/get-items/app.ts | 2 +- .../typescript/SampleApp/src/functions/put-item/app.ts | 6 +++--- code/powertools/typescript/SampleSolution/package.json | 4 ++-- .../SampleSolution/src/functions/get-by-id/app.ts | 2 +- .../SampleSolution/src/functions/get-items/app.ts | 2 +- .../typescript/SampleSolution/src/functions/put-item/app.ts | 6 +++--- code/powertools/typescript/SampleSolution/template.yaml | 6 +++--- 9 files changed, 17 insertions(+), 17 deletions(-) diff --git a/code/powertools/typescript/SampleApp/package.json b/code/powertools/typescript/SampleApp/package.json index de467b8..935f11d 100644 --- a/code/powertools/typescript/SampleApp/package.json +++ b/code/powertools/typescript/SampleApp/package.json @@ -18,8 +18,8 @@ "@aws-lambda-powertools/tracer": "^1.13.1", "@aws-sdk/lib-dynamodb": "^3.418.0", "aws-lambda": "^1.0.7", - "aws-sdk": "^3.420.0", - "esbuild": "^0.14.14", + "aws-sdk": "^2.1489.0", + "esbuild": "^0.19.5", "tslib": "^2.6.2" }, "devDependencies": { 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 index 89e209e..62abcce 100644 --- a/code/powertools/typescript/SampleApp/src/functions/get-by-id/app.ts +++ b/code/powertools/typescript/SampleApp/src/functions/get-by-id/app.ts @@ -2,7 +2,7 @@ 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({ region: "us-east-1" }); +const client = new DynamoDBClient({}); const ddbDocClient = DynamoDBDocument.from(client); diff --git a/code/powertools/typescript/SampleApp/src/functions/get-items/app.ts b/code/powertools/typescript/SampleApp/src/functions/get-items/app.ts index 0f68224..fd2f409 100644 --- a/code/powertools/typescript/SampleApp/src/functions/get-items/app.ts +++ b/code/powertools/typescript/SampleApp/src/functions/get-items/app.ts @@ -2,7 +2,7 @@ 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({ region: "us-east-1" }); +const client = new DynamoDBClient({}); const ddbDocClient = DynamoDBDocument.from(client); diff --git a/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts b/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts index 67b73e9..22b6a47 100644 --- a/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts +++ b/code/powertools/typescript/SampleApp/src/functions/put-item/app.ts @@ -2,7 +2,7 @@ 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({ region: "us-east-1" }); +const client = new DynamoDBClient({}); const ddbDocClient = DynamoDBDocument.from(client); @@ -42,8 +42,8 @@ const putItem = async (event) => { let response try { const body = JSON.parse(event.body) - const id = body.id.toString() - const name = body.name + const id = body.Id.toString() + const name = body.Name var params = { TableName: process.env.SAMPLE_TABLE, diff --git a/code/powertools/typescript/SampleSolution/package.json b/code/powertools/typescript/SampleSolution/package.json index 8b374ae..935f11d 100644 --- a/code/powertools/typescript/SampleSolution/package.json +++ b/code/powertools/typescript/SampleSolution/package.json @@ -18,8 +18,8 @@ "@aws-lambda-powertools/tracer": "^1.13.1", "@aws-sdk/lib-dynamodb": "^3.418.0", "aws-lambda": "^1.0.7", - "aws-sdk": "^2.1463.0", - "esbuild": "^0.14.14", + "aws-sdk": "^2.1489.0", + "esbuild": "^0.19.5", "tslib": "^2.6.2" }, "devDependencies": { 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 index 4c86448..23d4802 100644 --- a/code/powertools/typescript/SampleSolution/src/functions/get-by-id/app.ts +++ b/code/powertools/typescript/SampleSolution/src/functions/get-by-id/app.ts @@ -3,7 +3,7 @@ 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({ region: "us-east-1" }); +const client = new DynamoDBClient({}); const ddbDocClient = DynamoDBDocument.from(client); const logger = new Logger(); diff --git a/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts b/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts index b805043..8422b60 100644 --- a/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts +++ b/code/powertools/typescript/SampleSolution/src/functions/get-items/app.ts @@ -4,7 +4,7 @@ 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({ region: "us-east-1" }); +const client = new DynamoDBClient({}); const ddbDocClient = DynamoDBDocument.from(client); const logger = new Logger(); diff --git a/code/powertools/typescript/SampleSolution/src/functions/put-item/app.ts b/code/powertools/typescript/SampleSolution/src/functions/put-item/app.ts index c5adda3..f5338d2 100644 --- a/code/powertools/typescript/SampleSolution/src/functions/put-item/app.ts +++ b/code/powertools/typescript/SampleSolution/src/functions/put-item/app.ts @@ -5,7 +5,7 @@ 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({ region: "us-east-1" }); +const client = new DynamoDBClient({}); const ddbDocClient = DynamoDBDocument.from(client); const logger = new Logger(); @@ -90,8 +90,8 @@ const putItem = async (event) => { let response try { const body = JSON.parse(event.body) - const id = body.id - const name = body.name + const id = body.Id.toString() + const name = body.Name var params = { TableName: process.env.SAMPLE_TABLE, diff --git a/code/powertools/typescript/SampleSolution/template.yaml b/code/powertools/typescript/SampleSolution/template.yaml index 0d4d3c0..14bd13d 100644 --- a/code/powertools/typescript/SampleSolution/template.yaml +++ b/code/powertools/typescript/SampleSolution/template.yaml @@ -48,7 +48,7 @@ Resources: 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: /api/items + Path: /items Method: GET Metadata: # Manage esbuild properties BuildMethod: esbuild @@ -77,7 +77,7 @@ Resources: 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: /api/items/{id} + Path: /items/{id} Method: GET Metadata: # Manage esbuild properties BuildMethod: esbuild @@ -106,7 +106,7 @@ Resources: 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: /api/items + Path: /items Method: POST Metadata: # Manage esbuild properties BuildMethod: esbuild