Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { z } from "zod";
- const maxBigInt = 9223372036854775807n;
- // safeBigInt returns a validated zod bigint type.
- export function safeBigInt() {
- return z
- .string()
- .max(19)
- .regex(/^\d+$/)
- .transform((value, ctx) => {
- // By now we have a string containing a positive integer.
- try {
- const v = BigInt(value);
- // Check the range here instead of .pipe(z.bigint().max(maxBigInt)).
- // Otherwise ts-rest would attempt to marshal the bigint to JSON (in an error response) which fails.
- if (v > maxBigInt) {
- throw new Error("too big");
- }
- return v;
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- } catch (err) {
- ctx.addIssue({
- code: "invalid_type",
- expected: typeof 0n,
- received: typeof value,
- message: "Invalid BigInt value",
- });
- return 0n;
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement