Closed
Description
Use case
Problem Statement
When working with AWS Lambda through API Gateway or Lambda Function URLs, request bodies are commonly sent as stringified JSON. The current Parser utility doesn't handle this case elegantly, requiring developers to implement manual parsing or workarounds that compromise type safety.
Current Limitations
-
Stringified JSON Handling: When receiving a stringified JSON payload (common in API Gateway and Lambda Function URLs), we need to:
- Either manually parse the JSON before schema validation
- Or create complex nested schemas that don't preserve type information effectively
-
Type Inference: When using the parser with API Gateway or Function URL handlers:
- We lose the automatic response type inference that comes with
APIGatewayProxyHandlerV2
orAPIGatewayProxyEventV2
- Need to explicitly specify response types, adding unnecessary boilerplate
- We lose the automatic response type inference that comes with
Example of Current Issues
// Current approach with manual parsing - API Gateway or Function URL
const handler: APIGatewayProxyHandlerV2 = async (event) => {
const body = JSON.parse(event.body ?? "{}");
const filename = body.filename ?? "unknown";
// ... rest of the handler
};
// Current attempt with parser (suboptimal)
const schema = z.object({
body: z.string(), // Have to define as string, losing type information
// ... other event properties
});
const handler = middy()
.use(parser({ schema }))
.handler(async (event) => {
// Need manual parsing inside handler
const body = JSON.parse(event.body);
// Types are lost
});
Solution/User Experience
Proposed Solutions
1. Built-in JSON String Preprocessing
Add a built-in preprocessor for JSON string fields, similar to the approach discussed in zod discussions:
const schema = z.object({
body: jsonString(z.object({
filename: z.string()
}))
});
// Would automatically parse JSON and validate against schema
2. Enhanced Envelope Support
Add specific envelopes for common Lambda HTTP patterns:
const handler = middy()
.use(parser({
schema: mySchema,
envelope: HttpJsonBodyEnvelope // New envelope type that works for both API Gateway and Function URLs
}))
.handler(async (event) => {
// event.body is already parsed and typed
});
Benefits
- Remove the need for manual JSON parsing in handlers
- Single validation step that handles both parsing and schema validation
- Reduce boilerplate code in Lambda functions
- Fewer places where JSON parsing errors need to be handled
- Unified approach for both API Gateway and Lambda Function URLs
- Better developer experience with simplified request handling
Alternative solutions
No response
Acknowledgment
- This feature request meets Powertools for AWS Lambda (TypeScript) Tenets
- Should this be considered in other Powertools for AWS Lambda languages? i.e. Python, Java, and .NET
Future readers
Please react with 👍 and your use case to help us understand customer demand.