-
Notifications
You must be signed in to change notification settings - Fork 156
docs: refresh SAM examples #1180
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
4e54141
SAM Example: Symlink for src folder
bpauwels 22e62fa
SAM Example: Switched Instrumentations for 2 functions
bpauwels 93b34ac
various changes
bpauwels 7d9b827
fixed link in readme
bpauwels 559cd42
fixed eslint errors
bpauwels 96a2cbb
comments from @dreamorosi
bpauwels ebf7677
added constants.ts, fixed versions
bpauwels 5c5153d
removed samconfig.toml
bpauwels 59a2f10
fixed package.lock.json
bpauwels 34f038a
moved to nodejs18.x runtime, excluded aws-sdk, fixed get functions
bpauwels 13e3d46
Update examples/sam/template.yaml
dreamorosi 6c901ae
Update examples/sam/template.yaml
dreamorosi ef41935
fixed tests
bpauwels 87c22f5
Merge branch 'issue-1140' of https://github.com/bpauwels/aws-lambda-p…
bpauwels a4d867a
Merge branch 'main' into issue-1140
bpauwels bcf6c65
fixed package-lock.json
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import { DynamoDBClient, ScanCommand, GetItemCommand, PutItemCommand } from '@aws-sdk/client-dynamodb'; | ||
|
||
const dynamodbClientV3 = new DynamoDBClient({}); | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
export { | ||
dynamodbClientV3, | ||
ScanCommand, | ||
GetItemCommand, | ||
PutItemCommand | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger'; | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
import { Metrics, logMetrics } from '@aws-lambda-powertools/metrics'; | ||
import { Tracer, captureLambdaHandler } from '@aws-lambda-powertools/tracer'; | ||
import { LambdaInterface } from '@aws-lambda-powertools/commons'; | ||
|
||
const awsLambdaPowertoolsVersion = '1.4.1'; | ||
|
||
const defaultValues = { | ||
region: process.env.AWS_REGION || 'N/A', | ||
executionEnv: process.env.AWS_EXECUTION_ENV || 'N/A' | ||
}; | ||
|
||
const logger = new Logger({ | ||
persistentLogAttributes: { | ||
...defaultValues, | ||
logger: { | ||
name: '@aws-lambda-powertools/logger', | ||
version: awsLambdaPowertoolsVersion, | ||
} | ||
}, | ||
}); | ||
|
||
const metrics = new Metrics({ | ||
defaultDimensions: defaultValues | ||
}); | ||
|
||
const tracer = new Tracer(); | ||
|
||
export { | ||
logger, | ||
metrics, | ||
tracer, | ||
injectLambdaContext, | ||
logMetrics, | ||
captureLambdaHandler, | ||
LambdaInterface | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,24 @@ | ||
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda'; | ||
import { Metrics } from '@aws-lambda-powertools/metrics'; | ||
import { Logger } from '@aws-lambda-powertools/logger'; | ||
import { Tracer } from '@aws-lambda-powertools/tracer'; | ||
import { DocumentClient } from 'aws-sdk/clients/dynamodb'; | ||
import middy from '@middy/core'; | ||
import { logger, tracer, metrics, injectLambdaContext, logMetrics, captureLambdaHandler, } from './common/powertools'; | ||
import { dynamodbClientV3, ScanCommand } from './common/dynamodb-client'; | ||
import got from 'got'; | ||
|
||
// Create the PowerTools clients | ||
const metrics = new Metrics(); | ||
const logger = new Logger(); | ||
const tracer = new Tracer(); | ||
/* | ||
* | ||
* This example uses the Middy middleware instrumentation. | ||
* It is the best choice if your existing code base relies on the Middy middleware engine. | ||
* Powertools offers compatible Middy middleware to make this integration seamless. | ||
* Find more Information in the docs: https://awslabs.github.io/aws-lambda-powertools-typescript/ | ||
* | ||
*/ | ||
|
||
// Create DynamoDB DocumentClient and patch it for tracing | ||
const docClient = tracer.captureAWSClient(new DocumentClient()); | ||
// Patch DynamoDB client for tracing | ||
const docClient = tracer.captureAWSv3Client(dynamodbClientV3); | ||
|
||
// Get the DynamoDB table name from environment variables | ||
const tableName = process.env.SAMPLE_TABLE; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we move this in a |
||
|
||
/** | ||
* | ||
* Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format | ||
|
@@ -24,7 +28,7 @@ const tableName = process.env.SAMPLE_TABLE; | |
* @returns {Object} object - API Gateway Lambda Proxy Output Format | ||
* | ||
*/ | ||
export const getAllItemsHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => { | ||
const getAllItemsHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => { | ||
if (event.httpMethod !== 'GET') { | ||
throw new Error(`getAllItems only accepts GET method, you tried: ${event.httpMethod}`); | ||
} | ||
|
@@ -40,29 +44,45 @@ export const getAllItemsHandler = async (event: APIGatewayProxyEvent, context: C | |
tracer.annotateColdStart(); | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
tracer.addServiceNameAnnotation(); | ||
|
||
// Tracer: Add annotation for the awsRequestId | ||
// Tracer: Add awsRequestId as annotation | ||
tracer.putAnnotation('awsRequestId', context.awsRequestId); | ||
|
||
// Metrics: Capture cold start metrics | ||
metrics.captureColdStartMetric(); | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Logger: Add persistent attributes to each log statement | ||
logger.addPersistentLogAttributes({ | ||
// Logger: Append awsRequestId to each log statement | ||
logger.appendKeys({ | ||
awsRequestId: context.awsRequestId, | ||
}); | ||
|
||
// Request a sample random uuid from a webservice | ||
const res = await got('https://httpbin.org/uuid'); | ||
const uuid = JSON.parse(res.body).uuid; | ||
|
||
// 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); | ||
|
||
// Define response object | ||
let response; | ||
|
||
// get all items from the table (only first 1MB data, you can use `LastEvaluatedKey` to get the rest of data) | ||
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property | ||
// https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html | ||
let response; | ||
try { | ||
if (!tableName) { | ||
throw new Error('SAMPLE_TABLE environment variable is not set'); | ||
} | ||
|
||
const data = await docClient.scan({ | ||
const data = await docClient.send(new ScanCommand({ | ||
TableName: tableName | ||
}).promise(); | ||
})); | ||
|
||
const items = data.Items; | ||
|
||
// Logger: All log statements are written to CloudWatch | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
@@ -91,4 +111,13 @@ export const getAllItemsHandler = async (event: APIGatewayProxyEvent, context: C | |
logger.info(`response from: ${event.path} statusCode: ${response.statusCode} body: ${response.body}`); | ||
|
||
return response; | ||
}; | ||
}; | ||
|
||
// Wrap the handler with middy | ||
export const handler = middy(getAllItemsHandler) | ||
// Use the middleware by passing the Metrics instance as a parameter | ||
.use(logMetrics(metrics)) | ||
// Use the middleware by passing the Logger instance as a parameter | ||
.use(injectLambdaContext(logger, { logEvent: true })) | ||
// Use the middleware by passing the Tracer instance as a parameter | ||
.use(captureLambdaHandler(tracer)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.