forked from aws-samples/serverless-test-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
67 lines (58 loc) · 2.37 KB
/
app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
//SPDX-License-Identifier: MIT-0
/**
* Lambda Handler for the typescript apigw-lambda-dynamodb example
* This handler accepts an id that represents a persons name, and creates a "Hello {Name}!" message.
* The id and name associated with the name is stored in a DynamoDB Table.
* Additionally, when a message is created, the lambda logs the "Hello {Name}!" message to DynamoDB with a timestamp.
* The DynamoDB Table used is passed as an environment variable "DYNAMODB_TABLE_NAME"
*/
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
PutCommand,
DynamoDBDocumentClient,
GetCommand
} from "@aws-sdk/lib-dynamodb";
export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
let response: APIGatewayProxyResult;
// Getting the dynamoDB table name from environment variable
const dynamoDBTableName = process.env.DYNAMODB_TABLE_NAME;
// User id field is passed as a path parameter
let id = event.pathParameters.id;
const dynamodb = new DynamoDBClient({});
const ddb = DynamoDBDocumentClient.from(dynamodb);
// Get the entry based on the id
let params = {Key: {'PK': id, 'SK':'NAME#'}, TableName: dynamoDBTableName};
const data = await ddb.send(new GetCommand(params))
let helloMessage = "Hello ";
let statusCode = 200;
if (data.Item){
let person_name = data.Item.SK
helloMessage = helloMessage.concat(person_name)
}else{
helloMessage = "NOTFOUND: Name Not Found for ID".concat(id);
statusCode = 404
}
// Create a timestamp and log the message back to DynamoDB
var timestamp = String(Date.now());
const param = { Item: {'PK': id,'SK': 'TS#'+timestamp, 'data':helloMessage}, TableName: dynamoDBTableName};
await ddb.send(new PutCommand(param));
try {
response = {
statusCode: statusCode,
body: JSON.stringify({
helloMessage,
}),
};
} catch (err: unknown) {
console.error(err);
response = {
statusCode: 500,
body: JSON.stringify({
message: err instanceof Error ? err.message : 'some error happened',
}),
};
}
return response;
};