-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzod-parse.ts
34 lines (30 loc) · 1.08 KB
/
zod-parse.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
import { Observable, OperatorFunction } from 'rxjs';
import { ZodType, ZodTypeDef } from 'zod';
let zodParseCount = 0;
export function zodParse<T, R>(
schema: ZodType<R, ZodTypeDef, T>,
options: { strict: boolean } = { strict: false }
): OperatorFunction<T, R> {
const zodParseIndex = ++zodParseCount;
return (source: Observable<T>) =>
new Observable((subscriber) =>
source.subscribe({
next: (value) => {
const description = `${schema.description ?? `Zod parsing #${zodParseIndex}`}`;
const parsedValue = schema.safeParse(value);
if (parsedValue.success) {
subscriber.next(parsedValue.data);
} else {
if (options.strict) {
subscriber.error(new Error(`${description}:\n\n${parsedValue.error.message}`));
} else {
console.warn(`${description}:\n\n`, parsedValue.error);
subscriber.next(value as unknown as R);
}
}
},
error: (err) => subscriber.error(err),
complete: () => subscriber.complete(),
})
);
}