@aws-lambda-powertools/parser
Version:
The parser package for the Powertools for AWS Lambda (TypeScript) library.
44 lines (43 loc) • 1.31 kB
JavaScript
import { ParseError } from '../errors.js';
import { APIGatewayProxyEventV2Schema } from '../schemas/api-gatewayv2.js';
import { envelopeDiscriminator } from './envelope.js';
/**
* API Gateway V2 envelope to extract data within body key
*/
export const ApiGatewayV2Envelope = {
/**
* This is a discriminator to differentiate whether an envelope returns an array or an object
* @hidden
*/
[envelopeDiscriminator]: 'object',
parse(data, schema) {
try {
return APIGatewayProxyEventV2Schema.extend({
body: schema,
}).parse(data).body;
}
catch (error) {
throw new ParseError('Failed to parse API Gateway HTTP body', {
cause: error,
});
}
},
safeParse(data, schema) {
const result = APIGatewayProxyEventV2Schema.extend({
body: schema,
}).safeParse(data);
if (!result.success) {
return {
success: false,
error: new ParseError('Failed to parse API Gateway HTTP body', {
cause: result.error,
}),
originalEvent: data,
};
}
return {
success: true,
data: result.data.body,
};
},
};