1- import { parse } from './envelope.js' ;
2- import { z , ZodSchema } from 'zod' ;
3- import { DynamoDBStreamSchema } from '../schemas/dynamodb.js' ;
1+ import { z , type ZodSchema } from 'zod' ;
2+ import { DynamoDBStreamSchema } from '../schemas/index.js' ;
3+ import type { ParsedResult , ParsedResultError } from '../types/index.js' ;
4+ import { Envelope } from './envelope.js' ;
45
56type DynamoDBStreamEnvelopeResponse < T extends ZodSchema > = {
67 NewImage : z . infer < T > ;
@@ -13,16 +14,58 @@ type DynamoDBStreamEnvelopeResponse<T extends ZodSchema> = {
1314 * Note: Values are the parsed models. Images' values can also be None, and
1415 * length of the list is the record's amount in the original event.
1516 */
16- export const dynamoDDStreamEnvelope = < T extends ZodSchema > (
17- data : unknown ,
18- schema : T
19- ) : DynamoDBStreamEnvelopeResponse < T > [ ] => {
20- const parsedEnvelope = DynamoDBStreamSchema . parse ( data ) ;
17+ export class DynamoDBStreamEnvelope extends Envelope {
18+ public static parse < T extends ZodSchema > (
19+ data : unknown ,
20+ schema : T
21+ ) : DynamoDBStreamEnvelopeResponse < z . infer < T > > [ ] {
22+ const parsedEnvelope = DynamoDBStreamSchema . parse ( data ) ;
23+
24+ return parsedEnvelope . Records . map ( ( record ) => {
25+ return {
26+ NewImage : super . parse ( record . dynamodb . NewImage , schema ) ,
27+ OldImage : super . parse ( record . dynamodb . OldImage , schema ) ,
28+ } ;
29+ } ) ;
30+ }
31+
32+ public static safeParse < T extends ZodSchema > (
33+ data : unknown ,
34+ schema : T
35+ ) : ParsedResult {
36+ const parsedEnvelope = DynamoDBStreamSchema . safeParse ( data ) ;
37+
38+ if ( ! parsedEnvelope . success ) {
39+ return {
40+ success : false ,
41+ error : parsedEnvelope . error ,
42+ originalEvent : data ,
43+ } ;
44+ }
45+ const parsedLogEvents : DynamoDBStreamEnvelopeResponse < z . infer < T > > [ ] = [ ] ;
46+
47+ for ( const record of parsedEnvelope . data . Records ) {
48+ const parsedNewImage = super . safeParse ( record . dynamodb . NewImage , schema ) ;
49+ const parsedOldImage = super . safeParse ( record . dynamodb . OldImage , schema ) ;
50+ if ( ! parsedNewImage . success || ! parsedOldImage . success ) {
51+ return {
52+ success : false ,
53+ error : ! parsedNewImage . success
54+ ? parsedNewImage . error
55+ : ( parsedOldImage as ParsedResultError < unknown > ) . error ,
56+ originalEvent : data ,
57+ } ;
58+ } else {
59+ parsedLogEvents . push ( {
60+ NewImage : parsedNewImage . data ,
61+ OldImage : parsedOldImage . data ,
62+ } ) ;
63+ }
64+ }
2165
22- return parsedEnvelope . Records . map ( ( record ) => {
2366 return {
24- NewImage : parse ( record . dynamodb . NewImage , schema ) ,
25- OldImage : parse ( record . dynamodb . OldImage , schema ) ,
67+ success : true ,
68+ data : parsedLogEvents ,
2669 } ;
27- } ) ;
28- } ;
70+ }
71+ }
0 commit comments