@aws-lambda-powertools/parser
Version:
The parser package for the Powertools for AWS Lambda (TypeScript) library.
85 lines (84 loc) • 1.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DynamoDBMarshalled = void 0;
const unmarshallDynamoDB_1 = require("@aws-lambda-powertools/commons/utils/unmarshallDynamoDB");
const zod_1 = require("zod");
/**
* A helper function to unmarshall DynamoDB stream events and validate them against a schema.
*
* @example
* ```typescript
* const mySchema = z.object({
* id: z.string(),
* name: z.string(),
* });
* const eventSchema = DynamoDBStreamSchema.extend({
* Records: z.array(
* DynamoDBStreamRecord.extend({
* dynamodb: z.object({
* NewImage: DynamoDBMarshalled(mySchema).optional(),
* }),
* })
* ),
* });
* type eventSchema = z.infer<typeof extendedSchema>;
* ```
* For example, if you have a DynamoDB stream event like the following:
*
* ```json
* {
* "Records": [
* {
* "dynamodb": {
* "NewImage": {
* "id": {
* "S": "12345"
* },
* "name": {
* "S": "John Doe"
* }
* }
* }
* }
* ]
* }
* ```
* Resulting in:
*
* ```json
* {
* "Records": [
* {
* "dynamodb": {
* "NewImage": {
* "id": "12345",
* "name": "John Doe"
* }
* }
* }
* ]
* }
* ```
*
* @param schema - The schema to validate the JSON string against
*/
const DynamoDBMarshalled = (schema) => zod_1.z
.union([
zod_1.z.custom(),
zod_1.z.record(zod_1.z.string(), zod_1.z.custom()),
])
.transform((str, ctx) => {
try {
return (0, unmarshallDynamoDB_1.unmarshallDynamoDB)(str);
}
catch {
ctx.addIssue({
code: 'custom',
message: 'Could not unmarshall DynamoDB stream record',
fatal: true,
});
return zod_1.z.NEVER;
}
})
.pipe(schema);
exports.DynamoDBMarshalled = DynamoDBMarshalled;