Skip to content

Commit 54f9b17

Browse files
authored
docs(jmespath): add utility docs (#2187)
1 parent a8dc5fa commit 54f9b17

17 files changed

+673
-3
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"Records": [
3+
{
4+
"messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78",
5+
"receiptHandle": "MessageReceiptHandle",
6+
"body": "{\"customerId\":\"dd4649e6-2484-4993-acb8-0f9123103394\",\"booking\":{\"id\":\"5b2c4803-330b-42b7-811a-c68689425de1\",\"reference\":\"ySz7oA\",\"outboundFlightId\":\"20c0d2f2-56a3-4068-bf20-ff7703db552d\"},\"payment\":{\"receipt\":\"https://pay.stripe.com/receipts/acct_1Dvn7pF4aIiftV70/ch_3JTC14F4aIiftV700iFq2CHB/rcpt_K7QsrFln9FgFnzUuBIiNdkkRYGxUL0X\",\"amount\":100}}",
7+
"attributes": {
8+
"ApproximateReceiveCount": "1",
9+
"SentTimestamp": "1523232000000",
10+
"SenderId": "123456789012",
11+
"ApproximateFirstReceiveTimestamp": "1523232000001"
12+
},
13+
"messageAttributes": {},
14+
"md5OfBody": "7b270e59b47ff90a553787216d55d91d",
15+
"eventSource": "aws:sqs",
16+
"eventSourceARN": "arn:aws:sqs:us-east-1:123456789012:MyQueue",
17+
"awsRegion": "us-east-1"
18+
}
19+
]
20+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import {
2+
extractDataFromEnvelope,
3+
SQS,
4+
} from '@aws-lambda-powertools/jmespath/envelopes';
5+
import { Logger } from '@aws-lambda-powertools/logger';
6+
import type { SQSEvent } from 'aws-lambda';
7+
8+
const logger = new Logger();
9+
10+
type MessageBody = {
11+
customerId: string;
12+
};
13+
14+
export const handler = async (event: SQSEvent): Promise<void> => {
15+
const records = extractDataFromEnvelope<Array<MessageBody>>(event, SQS);
16+
for (const record of records) {
17+
// records is now a list containing the deserialized body of each message
18+
const { customerId } = record;
19+
logger.appendKeys({ customerId });
20+
}
21+
};
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"body": "{\"customerId\":\"dd4649e6-2484-4993-acb8-0f9123103394\"}",
3+
"deeplyNested": [
4+
{
5+
"someData": [1, 2, 3]
6+
}
7+
]
8+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { extractDataFromEnvelope } from '@aws-lambda-powertools/jmespath/envelopes';
2+
3+
type MyEvent = {
4+
body: string; // "{\"customerId\":\"dd4649e6-2484-4993-acb8-0f9123103394\"}"
5+
deeplyNested: Array<{ someData: number[] }>;
6+
};
7+
8+
type MessageBody = {
9+
customerId: string;
10+
};
11+
12+
export const handler = async (event: MyEvent): Promise<unknown> => {
13+
const payload = extractDataFromEnvelope<MessageBody>(
14+
event,
15+
'powertools_json(body)'
16+
);
17+
const { customerId } = payload; // now deserialized
18+
19+
// also works for fetching and flattening deeply nested data
20+
const someData = extractDataFromEnvelope<number[]>(
21+
event,
22+
'deeplyNested[*].someData[]'
23+
);
24+
25+
return {
26+
customerId,
27+
message: 'success',
28+
context: someData,
29+
statusCode: 200,
30+
};
31+
};
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { extractDataFromEnvelope } from '@aws-lambda-powertools/jmespath/envelopes';
2+
import { Logger } from '@aws-lambda-powertools/logger';
3+
4+
const logger = new Logger();
5+
6+
export const handler = async (event: { payload: string }): Promise<void> => {
7+
const logGroup = extractDataFromEnvelope<string>(
8+
event, // (1)!
9+
'powertools_base64_gzip(payload) | powertools_json(@).logGroup'
10+
);
11+
12+
logger.info('Log group name', { logGroup }); // (2)!
13+
};
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"payload": "H4sIACZAXl8C/52PzUrEMBhFX2UILpX8tPbHXWHqIOiq3Q1F0ubrWEiakqTWofTdTYYB0YWL2d5zvnuTFellBIOedoiyKH5M0iwnlKH7HZL6dDB6ngLDfLFYctUKjie9gHFaS/sAX1xNEq525QxwFXRGGMEkx4Th491rUZdV3YiIZ6Ljfd+lfSyAtZloacQgAkqSJCGhxM6t7cwwuUGPz4N0YKyvO6I9WDeMPMSo8Z4Ca/kJ6vMEYW5f1MX7W1lVxaG8vqX8hNFdjlc0iCBBSF4ERT/3Pl7RbMGMXF2KZMh/C+gDpNS7RRsp0OaRGzx0/t8e0jgmcczyLCWEePhni/23JWalzjdu0a3ZvgEaNLXeugEAAA=="
3+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { extractDataFromEnvelope } from '@aws-lambda-powertools/jmespath/envelopes';
2+
import { Logger } from '@aws-lambda-powertools/logger';
3+
4+
const logger = new Logger();
5+
6+
export const handler = async (event: { payload: string }): Promise<void> => {
7+
const data = extractDataFromEnvelope<string>(
8+
event,
9+
'powertools_json(powertools_base64(payload))'
10+
);
11+
12+
logger.info('Decoded payload', { data }); // (1)!
13+
};
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"payload": "eyJ1c2VyX2lkIjogMTIzLCAicHJvZHVjdF9pZCI6IDEsICJxdWFudGl0eSI6IDIsICJwcmljZSI6IDEwLjQwLCAiY3VycmVuY3kiOiAiVVNEIn0="
3+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Records": [
3+
{
4+
"application": "app",
5+
"datetime": "2022-01-01T00:00:00.000Z",
6+
"notification": "GyYA+AXhZKk/K5DkanoQSTYpSKMwwxXh8DRWVo9A1hLqAQ=="
7+
}
8+
]
9+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { fromBase64 } from '@aws-lambda-powertools/commons/utils/base64';
2+
import { extractDataFromEnvelope } from '@aws-lambda-powertools/jmespath/envelopes';
3+
import { PowertoolsFunctions } from '@aws-lambda-powertools/jmespath/functions';
4+
import { Logger } from '@aws-lambda-powertools/logger';
5+
import { brotliDecompressSync } from 'node:zlib';
6+
7+
const logger = new Logger();
8+
9+
// prettier-ignore
10+
class CustomFunctions extends PowertoolsFunctions {
11+
@PowertoolsFunctions.signature({ // (1)!
12+
argumentsSpecs: [['string']],
13+
variadic: false,
14+
})
15+
public funcDecodeBrotliCompression(value: string): string { // (2)!
16+
const encoded = fromBase64(value, 'base64');
17+
const uncompressed = brotliDecompressSync(encoded);
18+
19+
return uncompressed.toString();
20+
}
21+
}
22+
23+
export const handler = async (event: { payload: string }): Promise<void> => {
24+
const message = extractDataFromEnvelope<string>(
25+
event,
26+
'Records[*].decode_brotli_compression(notification) | [*].powertools_json(@).message',
27+
{ customFunctions: new CustomFunctions() }
28+
);
29+
30+
logger.info('Decoded message', { message });
31+
};
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
{
2+
"version": "2.0",
3+
"routeKey": "ANY /createpayment",
4+
"rawPath": "/createpayment",
5+
"rawQueryString": "",
6+
"headers": {
7+
"Header1": "value1",
8+
"Header2": "value2"
9+
},
10+
"requestContext": {
11+
"accountId": "123456789012",
12+
"apiId": "api-id",
13+
"domainName": "id.execute-api.us-east-1.amazonaws.com",
14+
"domainPrefix": "id",
15+
"http": {
16+
"method": "POST",
17+
"path": "/createpayment",
18+
"protocol": "HTTP/1.1",
19+
"sourceIp": "ip",
20+
"userAgent": "agent"
21+
},
22+
"requestId": "id",
23+
"routeKey": "ANY /createpayment",
24+
"stage": "$default",
25+
"time": "10/Feb/2021:13:40:43 +0000",
26+
"timeEpoch": 1612964443723
27+
},
28+
"body": "{\"user\":\"xyz\",\"product_id\":\"123456789\"}",
29+
"isBase64Encoded": false
30+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import {
2+
IdempotencyConfig,
3+
makeIdempotent,
4+
} from '@aws-lambda-powertools/idempotency';
5+
import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb';
6+
import type { APIGatewayEvent } from 'aws-lambda';
7+
import { randomUUID } from 'node:crypto';
8+
9+
const persistenceStore = new DynamoDBPersistenceLayer({
10+
tableName: 'IdempotencyTable',
11+
});
12+
13+
export const handler = makeIdempotent(
14+
async (event: APIGatewayEvent) => {
15+
const body = JSON.parse(event.body || '{}');
16+
const { user, productId } = body;
17+
18+
const result = await createSubscriptionPayment(user, productId);
19+
20+
return {
21+
statusCode: 200,
22+
body: JSON.stringify({
23+
paymentId: result.id,
24+
message: 'success',
25+
}),
26+
};
27+
},
28+
{
29+
persistenceStore,
30+
config: new IdempotencyConfig({
31+
eventKeyJmesPath: 'powertools_json(body)',
32+
}),
33+
}
34+
);
35+
36+
const createSubscriptionPayment = async (
37+
user: string,
38+
productId: string
39+
): Promise<{ id: string; message: string }> => {
40+
const payload = { user, productId };
41+
const response = await fetch('https://httpbin.org/anything', {
42+
method: 'POST',
43+
body: JSON.stringify(payload),
44+
});
45+
46+
if (!response.ok) {
47+
throw new Error('Failed to create subscription payment');
48+
}
49+
50+
return { id: randomUUID(), message: 'paid' };
51+
};

docs/snippets/tsconfig.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,11 @@
2727
"@aws-lambda-powertools/idempotency/middleware": [
2828
"../../packages/idempotency/lib/middleware"
2929
],
30-
"@aws-lambda-powertools/batch": ["../../packages/batch/lib"]
30+
"@aws-lambda-powertools/batch": ["../../packages/batch/lib"],
31+
"@aws-lambda-powertools/jmespath": ["../../packages/jmespath/lib"],
32+
"@aws-lambda-powertools/jmespath/envelopes": [
33+
"../../packages/jmespath/lib/envelopes"
34+
]
3135
}
3236
}
3337
}

0 commit comments

Comments
 (0)