Package Exports
- @lcsga/zod-operators
- @lcsga/zod-operators/src/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@lcsga/zod-operators) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@lcsga/zod-operators
This package provides a custom RxJS operator, used to empower the use of zod schemas alongside RxJS observables.
zodParse: This operator is usefull to parse zod schemas within an RxJS stream, in order to check types at runtime.
zodParse<T>(schema: ZodSchema<T>, options?: { strict?: boolean }): MonoTypeOperatorFunction<T>
argument type description schemaZodSchema<T>The schema to provide for the parsing.
A description can also be provided to improve the debugging by calling thedescribe()method to it.options{ strict: boolean }Optional. Default is {}.
A configuration object to modify the behavior of the operator.
Example:
const GithubUserSchema = z.object({ id: z.string().uuid(), login: z.string(), }); type GithubUser = z.infer<typeof GithubUserSchema>; fromFetch<GithubUser[]>('https://api.github.com/users?per_page=5', { selector: (res) => res.json() }) .pipe(zodParse(GithubUserSchema.array())) .subscribe(console.log);
Since the id of a Github user is of type
numberand since the zodParse is not strict by default, theconsole.logwill return the object fetched without any parsing and console will send a warning:ZodError: [ { "code": "invalid_type", "expected": "string", "received": "number", "path": [ 0, "id" ], "message": "Expected string, received number" }, { "code": "invalid_type", "expected": "string", "received": "number", "path": [ 1, "id" ], "message": "Expected string, received number" }, { "code": "invalid_type", "expected": "string", "received": "number", "path": [ 2, "id" ], "message": "Expected string, received number" }, { "code": "invalid_type", "expected": "string", "received": "number", "path": [ 3, "id" ], "message": "Expected string, received number" }, { "code": "invalid_type", "expected": "string", "received": "number", "path": [ 4, "id" ], "message": "Expected string, received number" } ]If we want to throw an error instead of a simple warning, we can pass an
optionsobject as the second argument and setstricttotrue:fromFetch<GithubUser[]>('https://api.github.com/users?per_page=5', { selector: (res) => res.json() }) .pipe(zodParse(GithubUserSchema.array(), { strict: true })) .subscribe(console.log);
The error will be the same as in the warning above we won't receive any data in the
console.log