forked from aws-samples/aws-sdk-js-notes-app
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathgetNote.ts
40 lines (36 loc) · 1.34 KB
/
getNote.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
import { DynamoDBClient, GetItemCommand } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";
import { success, failure, not_found } from "./libs/response";
// eslint-disable-next-line no-unused-vars
import { APIGatewayEvent } from "aws-lambda";
export const handler = async (event: APIGatewayEvent) => {
const params = {
TableName: process.env.NOTES_TABLE_NAME || "",
// 'Key' defines the partition key and sort key of the item to be retrieved
// - 'noteId': path parameter
Key: marshall({ noteId: event.pathParameters?.id }),
};
try {
let client: DynamoDBClient;
if (process.env.LOCALSTACK_HOSTNAME) {
const localStackConfig = {
endpoint: `http://${process.env.LOCALSTACK_HOSTNAME}:${process.env.EDGE_PORT}`,
region: "us-east-1", // Change the region as per your setup
};
client = new DynamoDBClient(localStackConfig);
} else {
// Use the default AWS configuration
client = new DynamoDBClient({});
}
const result = await client.send(new GetItemCommand(params));
if (result.Item) {
// Return the retrieved item
return success(unmarshall(result.Item));
} else {
return not_found({ status: false, error: "Item not found." });
}
} catch (e) {
console.log(e);
return failure({ status: false });
}
};