|
| 1 | +import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda'; |
| 2 | +import { Metrics } from '@aws-lambda-powertools/metrics'; |
| 3 | +import { Logger } from '@aws-lambda-powertools/logger'; |
| 4 | +import { Tracer } from '@aws-lambda-powertools/tracer'; |
| 5 | +import { DocumentClient } from 'aws-sdk/clients/dynamodb'; |
| 6 | + |
| 7 | +// Create the PowerTools clients |
| 8 | +const metrics = new Metrics(); |
| 9 | +const logger = new Logger(); |
| 10 | +const tracer = new Tracer(); |
| 11 | + |
| 12 | +// Create DynamoDB DocumentClient and patch it for tracing |
| 13 | +const docClient = tracer.captureAWSClient(new DocumentClient()); |
| 14 | + |
| 15 | +// Get the DynamoDB table name from environment variables |
| 16 | +const tableName = process.env.SAMPLE_TABLE; |
| 17 | + |
| 18 | +/** |
| 19 | + * |
| 20 | + * Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format |
| 21 | + * @param {Object} event - API Gateway Lambda Proxy Input Format |
| 22 | + * |
| 23 | + * Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html |
| 24 | + * @returns {Object} object - API Gateway Lambda Proxy Output Format |
| 25 | + * |
| 26 | + */ |
| 27 | + |
| 28 | +export const getByIdHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => { |
| 29 | + if (event.httpMethod !== 'GET') { |
| 30 | + throw new Error(`getById only accepts GET method, you tried: ${event.httpMethod}`); |
| 31 | + } |
| 32 | + // Tracer: Get facade segment created by AWS Lambda |
| 33 | + const segment = tracer.getSegment(); |
| 34 | + |
| 35 | + // Tracer: Create subsegment for the function & set it as active |
| 36 | + const handlerSegment = segment.addNewSubsegment(`## ${process.env._HANDLER}`); |
| 37 | + tracer.setSegment(handlerSegment); |
| 38 | + |
| 39 | + // Tracer: Annotate the subsegment with the cold start & serviceName |
| 40 | + tracer.annotateColdStart(); |
| 41 | + tracer.addServiceNameAnnotation(); |
| 42 | + |
| 43 | + // Tracer: Add annotation for the awsRequestId |
| 44 | + tracer.putAnnotation('awsRequestId', context.awsRequestId); |
| 45 | + |
| 46 | + // Metrics: Capture cold start metrics |
| 47 | + metrics.captureColdStartMetric(); |
| 48 | + |
| 49 | + // Logger: Add persistent attributes to each log statement |
| 50 | + logger.addPersistentLogAttributes({ |
| 51 | + awsRequestId: context.awsRequestId, |
| 52 | + }); |
| 53 | + |
| 54 | + // Get the item from the table |
| 55 | + // https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property |
| 56 | + let response; |
| 57 | + try { |
| 58 | + if (!tableName) { |
| 59 | + throw new Error('SAMPLE_TABLE environment variable is not set'); |
| 60 | + } |
| 61 | + if (!event.pathParameters) { |
| 62 | + throw new Error('event does not contain pathParameters') |
| 63 | + } |
| 64 | + if (!event.pathParameters.id) { |
| 65 | + throw new Error('PathParameter id is missing') |
| 66 | + } |
| 67 | + |
| 68 | + const data = await docClient.get({ |
| 69 | + TableName: tableName, |
| 70 | + Key: { id: event.pathParameters.id }, |
| 71 | + }).promise(); |
| 72 | + const item = data.Item; |
| 73 | + response = { |
| 74 | + statusCode: 200, |
| 75 | + body: JSON.stringify(item) |
| 76 | + }; |
| 77 | + } catch (err) { |
| 78 | + tracer.addErrorAsMetadata(err as Error); |
| 79 | + logger.error('Error reading from table. ' + err); |
| 80 | + response = { |
| 81 | + statusCode: 500, |
| 82 | + body: JSON.stringify({ 'error': 'Error reading from table.' }) |
| 83 | + }; |
| 84 | + } |
| 85 | + |
| 86 | + // Tracer: Close subsegment (the AWS Lambda one is closed automatically) |
| 87 | + handlerSegment.close(); // (## index.handler) |
| 88 | + |
| 89 | + // Tracer: Set the facade segment as active again (the one created by AWS Lambda) |
| 90 | + tracer.setSegment(segment); |
| 91 | + |
| 92 | + // All log statements are written to CloudWatch |
| 93 | + logger.info(`response from: ${event.path} statusCode: ${response.statusCode} body: ${response.body}`); |
| 94 | + |
| 95 | + return response; |
| 96 | +}; |
0 commit comments