Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions code/powertools/typescript/SampleApp/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
Original file line number Diff line number Diff line change
@@ -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<APIGatewayProxyResult> => {


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
}
Original file line number Diff line number Diff line change
@@ -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<APIGatewayProxyResult> => {


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
}
59 changes: 59 additions & 0 deletions code/powertools/typescript/SampleApp/src/functions/put-item/app.ts
Original file line number Diff line number Diff line change
@@ -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<APIGatewayProxyResult> => {

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
}
142 changes: 142 additions & 0 deletions code/powertools/typescript/SampleApp/template.yaml
Original file line number Diff line number Diff line change
@@ -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
Loading