Advertisement
Guest User

Typescript zod safeBigInt type

a guest
Dec 12th, 2024
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { z } from "zod";
  2.  
  3. const maxBigInt = 9223372036854775807n;
  4.  
  5. // safeBigInt returns a validated zod bigint type.
  6. export function safeBigInt() {
  7.   return z
  8.     .string()
  9.     .max(19)
  10.     .regex(/^\d+$/)
  11.     .transform((value, ctx) => {
  12.       // By now we have a string containing a positive integer.
  13.       try {
  14.         const v = BigInt(value);
  15.         // Check the range here instead of .pipe(z.bigint().max(maxBigInt)).
  16.         // Otherwise ts-rest would attempt to marshal the bigint to JSON (in an error response) which fails.
  17.         if (v > maxBigInt) {
  18.           throw new Error("too big");
  19.         }
  20.         return v;
  21.         // eslint-disable-next-line @typescript-eslint/no-unused-vars
  22.       } catch (err) {
  23.         ctx.addIssue({
  24.           code: "invalid_type",
  25.           expected: typeof 0n,
  26.           received: typeof value,
  27.           message: "Invalid BigInt value",
  28.         });
  29.  
  30.         return 0n;
  31.       }
  32.     });
  33. }
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement