-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathhelpers.ts
41 lines (39 loc) · 1.03 KB
/
helpers.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
import { type ZodTypeAny, z } from 'zod';
/**
* A helper function to parse a JSON string and validate it against a schema.
* Use it for built-in schemas like `AlbSchema`, `ApiGatewaySchema`, etc. to extend them with your customer schema.
*
* @example
* ```typescript
* import { JSONStringified } from '@aws-lambda-powertools/parser/helpers';
* import { AlbSchema } from '@aws-lambda-powertools/parser/schemas';
* import { z } from 'zod';
*
* const customSchema = z.object({
* name: z.string(),
* age: z.number(),
* });
*
* const extendedSchema = AlbSchema.extend({
* body: JSONStringified(customSchema),
* });
*
* ```
*
* @param schema - The schema to validate the JSON string against
*/
const JSONStringified = <T extends ZodTypeAny>(schema: T) =>
z
.string()
.transform((str, ctx) => {
try {
return JSON.parse(str);
} catch (err) {
ctx.addIssue({
code: 'custom',
message: 'Invalid JSON',
});
}
})
.pipe(schema);
export { JSONStringified };