-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathget-by-id.ts
110 lines (92 loc) · 3.83 KB
/
get-by-id.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
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
import { tableName } from './common/constants';
import { logger, tracer, metrics } from './common/powertools';
import { LambdaInterface } from '@aws-lambda-powertools/commons';
import { docClient } from './common/dynamodb-client';
import { GetCommand } from '@aws-sdk/lib-dynamodb';
import { default as request } from 'phin';
/*
*
* This example uses the Method decorator instrumentation.
* Use TypeScript method decorators if you prefer writing your business logic using TypeScript Classes.
* If you aren’t using Classes, this requires the most significant refactoring.
* Find more Information in the docs: https://awslabs.github.io/aws-lambda-powertools-typescript/
*
* 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
*
*/
class Lambda implements LambdaInterface {
@tracer.captureMethod()
public async getUuid(): Promise<string> {
// Request a sample random uuid from a webservice
const res = await request<{ uuid: string }>({
url: 'https://httpbin.org/uuid',
parse: 'json',
});
const { uuid } = res.body;
return uuid;
}
@tracer.captureLambdaHandler({ captureResponse: false }) // by default the tracer would add the response as metadata on the segment, but there is a chance to hit the 64kb segment size limit. Therefore set captureResponse: false
@logger.injectLambdaContext({ logEvent: true })
@metrics.logMetrics({ throwOnEmptyMetrics: false, captureColdStartMetric: true })
public async handler(event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> {
if (event.httpMethod !== 'GET') {
throw new Error(`getById only accepts GET method, you tried: ${event.httpMethod}`);
}
// Tracer: Add awsRequestId as annotation
tracer.putAnnotation('awsRequestId', context.awsRequestId);
// Logger: Append awsRequestId to each log statement
logger.appendKeys({
awsRequestId: context.awsRequestId,
});
// Call the getUuid function
const uuid = await this.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);
// Get the item from the table
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property
try {
if (!tableName) {
throw new Error('SAMPLE_TABLE environment variable is not set');
}
if (!event.pathParameters) {
throw new Error('event does not contain pathParameters');
}
if (!event.pathParameters.id) {
throw new Error('PathParameter id is missing');
}
const data = await docClient.send(new GetCommand({
TableName: tableName,
Key: {
id: event.pathParameters.id
}
}));
const item = data.Item;
logger.info(`Response ${event.path}`, {
statusCode: 200,
body: item,
});
return {
statusCode: 200,
body: JSON.stringify(item)
};
} catch (err) {
tracer.addErrorAsMetadata(err as Error);
logger.error('Error reading from table. ' + err);
return {
statusCode: 500,
body: JSON.stringify({ 'error': 'Error reading from table.' })
};
}
}
}
const handlerClass = new Lambda();
export const handler = handlerClass.handler.bind(handlerClass);