Skip to content

docs: add parser example for built-in extension using transform and pipe #2892

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 1 addition & 13 deletions docs/core/event-handler/api-gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,5 @@ This is the sample infrastructure for API Gateway and Lambda Function URLs we ar

???+ info "There is no additional permissions or dependencies required to use this utility."

=== "API Gateway SAM Template"

```yaml title="AWS Serverless Application Model (SAM) example"
--8<-- "examples/snippets/event-handler/rest/templates/template.yaml"
```

=== "Lambda Function URL SAM Template"

```yaml title="AWS Serverless Application Model (SAM) example"
--8<-- "examples/event_handler_lambda_function_url/sam/template.yaml"
```

<!-- remove line below while editing this doc & put it back until the doc has reached its first draft -->
<!-- markdownlint-disable MD043 -->
<!-- markdownlint-disable MD043 -->
17 changes: 17 additions & 0 deletions docs/utilities/parser.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,23 @@ You can extend every built-in schema to include your own schema, and yet have al
--8<-- "examples/snippets/parser/examplePayload.json"
```

For scenarios where you have a stringiied JSON payload, you can extend the built-in schema using `.transform()` and `.pipe()` method.

=== "APIGatewayProxyEventSchema"

```typescript hl_lines="24-34"
--8<-- "examples/snippets/parser/extendAPIGatewaySchema.ts"
```

1. parse the `body` inside `transform` method
2. chain your custom schema to `pipe` operation

=== "Example Payload for API Gateway Event"

```json
--8<-- "examples/snippets/parser/exampleAPIGatewayPayload.json"
```

## Envelopes

When trying to parse your payload you might encounter the following situations:
Expand Down
81 changes: 81 additions & 0 deletions examples/snippets/parser/exampleAPIGatewayPayload.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
{
"version": "1.0",
"resource": "/my/path",
"path": "/my/path",
"httpMethod": "GET",
"headers": {
"Header1": "value1",
"Header2": "value2",
"Origin": "https://aws.amazon.com"
},
"multiValueHeaders": {
"Header1": [
"value1"
],
"Header2": [
"value1",
"value2"
]
},
"queryStringParameters": {
"parameter1": "value1",
"parameter2": "value"
},
"multiValueQueryStringParameters": {
"parameter1": [
"value1",
"value2"
],
"parameter2": [
"value"
]
},
"requestContext": {
"accountId": "123456789012",
"apiId": "id",
"authorizer": {
"claims": null,
"scopes": null
},
"domainName": "id.execute-api.us-east-1.amazonaws.com",
"domainPrefix": "id",
"extendedRequestId": "request-id",
"httpMethod": "GET",
"identity": {
"accessKey": null,
"accountId": null,
"caller": null,
"cognitoAuthenticationProvider": null,
"cognitoAuthenticationType": null,
"cognitoIdentityId": null,
"cognitoIdentityPoolId": null,
"principalOrgId": null,
"sourceIp": "192.168.0.1",
"user": null,
"userAgent": "user-agent",
"userArn": null,
"clientCert": {
"clientCertPem": "CERT_CONTENT",
"subjectDN": "www.example.com",
"issuerDN": "Example issuer",
"serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
"validity": {
"notBefore": "May 28 12:30:02 2019 GMT",
"notAfter": "Aug 5 09:36:04 2021 GMT"
}
}
},
"path": "/my/path",
"protocol": "HTTP/1.1",
"requestId": "id=",
"requestTime": "04/Mar/2020:19:15:17 +0000",
"requestTimeEpoch": 1583349317135,
"resourceId": null,
"resourcePath": "/my/path",
"stage": "$default"
},
"pathParameters": null,
"stageVariables": null,
"body": "{\"id\":10876546789,\"description\":\"My order\",\"items\":[{\"id\":1015938732,\"quantity\":1,\"description\":\"item xpto\"}]}",
"isBase64Encoded": false
}
50 changes: 50 additions & 0 deletions examples/snippets/parser/extendAPIGatewaySchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import { Logger } from '@aws-lambda-powertools/logger';
import { parser } from '@aws-lambda-powertools/parser';
import { APIGatewayProxyEventSchema } from '@aws-lambda-powertools/parser/schemas/api-gateway';
import type { Context } from 'aws-lambda';
import { z } from 'zod';

const logger = new Logger();

const orderSchema = z.object({
id: z.number().positive(),
description: z.string(),
items: z.array(
z.object({
id: z.number().positive(),
quantity: z.number(),
description: z.string(),
})
),
});

const orderEventSchema = APIGatewayProxyEventSchema.extend({
body: z
.string()
.transform((str, ctx) => {
try {
return JSON.parse(str); // (1)!
} catch (err) {
ctx.addIssue({
code: 'custom',
message: 'Invalid JSON',
});
}
})
.pipe(orderSchema), // (2)!
});

type OrderEvent = z.infer<typeof orderEventSchema>;

class Lambda implements LambdaInterface {
@parser({ schema: orderEventSchema })
public async handler(event: OrderEvent, _context: Context): Promise<void> {
for (const item of event.body.items) {
// process OrderItem
logger.info('Processing item', { item });
}
}
}
const myFunction = new Lambda();
export const handler = myFunction.handler.bind(myFunction);