-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathput-item.ts
122 lines (104 loc) · 3.6 KB
/
put-item.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import { PutCommand } from '@aws-sdk/lib-dynamodb';
import {
APIGatewayProxyEvent,
APIGatewayProxyResult,
Context,
} from 'aws-lambda';
import type { Subsegment } from 'aws-xray-sdk-core';
import { tableName } from './common/constants';
import { docClient } from './common/dynamodb-client';
import { getUuid } from './common/getUuid';
import { logger, metrics, tracer } from './common/powertools';
/**
*
* This example uses the manual instrumentation.
*
* Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
* @param {APIGatewayProxyEvent} event - API Gateway Lambda Proxy Input Format
*
* Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
* @returns {Promise<APIGatewayProxyResult>} object - API Gateway Lambda Proxy Output Format
*
*/
export const handler = async (
event: APIGatewayProxyEvent,
context: Context
): Promise<APIGatewayProxyResult> => {
if (event.httpMethod !== 'POST') {
throw new Error(
`putItem only accepts POST method, you tried: ${event.httpMethod}`
);
}
// Logger: Log the incoming event
logger.info('Lambda invocation event', { event });
// Tracer: Get facade segment created by AWS Lambda
const segment = tracer.getSegment();
// Tracer: Create subsegment for the function & set it as active
let handlerSegment: Subsegment | undefined;
if (segment) {
handlerSegment = segment.addNewSubsegment(`## ${process.env._HANDLER}`);
tracer.setSegment(handlerSegment);
}
// Tracer: Annotate the subsegment with the cold start & serviceName
tracer.annotateColdStart();
tracer.addServiceNameAnnotation();
// Tracer: Add awsRequestId as annotation
tracer.putAnnotation('awsRequestId', context.awsRequestId);
// Metrics: Capture cold start metrics
metrics.captureColdStartMetric();
// Logger: Append awsRequestId to each log statement
logger.appendKeys({
awsRequestId: context.awsRequestId,
});
const uuid = await getUuid();
// Logger: Append uuid to each log statement
logger.appendKeys({ uuid });
// Tracer: Add uuid as annotation
tracer.putAnnotation('uuid', uuid);
// Metrics: Add uuid as metadata
metrics.addMetadata('uuid', uuid);
// Creates a new item, or replaces an old item with a new item
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property
try {
if (!tableName) {
throw new Error('SAMPLE_TABLE environment variable is not set');
}
if (!event.body) {
throw new Error('Event does not contain body');
}
// Get id and name from the body of the request
const body = JSON.parse(event.body);
const { id, name } = body;
await docClient.send(
new PutCommand({
TableName: tableName,
Item: {
id,
name,
},
})
);
logger.info(`Response ${event.path}`, {
statusCode: 200,
body,
});
return {
statusCode: 200,
body: JSON.stringify(body),
};
} catch (err) {
tracer.addErrorAsMetadata(err as Error);
logger.error('Error writing data to table. ' + err);
return {
statusCode: 500,
body: JSON.stringify({ error: 'Error writing data to table.' }),
};
} finally {
if (segment && handlerSegment) {
// Tracer: Close subsegment (the AWS Lambda one is closed automatically)
handlerSegment.close(); // (## index.handler)
// Tracer: Set the facade segment as active again (the one created by AWS Lambda)
tracer.setSegment(segment);
}
}
};