-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathparser.ts
74 lines (70 loc) · 2.31 KB
/
parser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import type { ZodSchema, z } from 'zod';
import { ParseError } from './errors.js';
import type { Envelope } from './types/index.js';
import type { ParseFunction } from './types/parser.js';
/**
* Parse the data using the provided schema, envelope and safeParse flag
*
* @example
* ```typescript
* import { z } from 'zod';
* import type { SqsEvent, ParsedResult } from '@aws-lambda-powertools/parser/types';
* import { SqsEnvelope } from '@aws-lambda-powertools/parser/types/envelopes';
* import { parse } from '@aws-lambda-powertools/parser';
*
* const Order = z.object({
* orderId: z.string(),
* description: z.string(),
* });
*
* const handler = async (event: SqsEvent, context: unknown): Promise<unknown> => {
* const parsedEvent = parse(event, SqsEnvelope, Order);
*
* const parsedSafe: ParsedResult<SqsEnvelope> = parse(event, SqsEnvelope, Order, true)
* }
* @param data the data to parse
* @param envelope the envelope to use, can be undefined
* @param schema the schema to use
* @param safeParse whether to use safeParse or not, if true it will return a ParsedResult with the original event if the parsing fails
*/
const parse: ParseFunction = <T extends ZodSchema, E extends Envelope>(
data: z.infer<T>,
envelope: E | undefined,
schema: T,
safeParse?: boolean
) => {
if (envelope && safeParse) {
return envelope.safeParse(data, schema);
}
if (envelope) {
return envelope.parse(data, schema);
}
if (safeParse) {
return safeParseSchema(data, schema);
}
try {
return schema.parse(data);
} catch (error) {
throw new ParseError('Failed to parse schema', { cause: error as Error });
}
};
/**
* Parse the data safely using the provided schema.
* This function will not throw an error if the parsing fails, instead it will return a ParsedResultError with the original event.
* Otherwise, it will return ParsedResultSuccess with the parsed data.
* @param data the data to parse
* @param schema the zod schema to use
*/
const safeParseSchema = <T extends ZodSchema>(data: z.infer<T>, schema: T) => {
const result = schema.safeParse(data);
return result.success
? result
: {
success: false,
error: new ParseError('Failed to parse schema safely', {
cause: result.error,
}),
originalEvent: data,
};
};
export { parse };