zod-utils.ts 617 B

12345678910111213141516171819
  1. import { type ZodSchema, type ZodTypeDef, z } from "zod";
  2. export const singletonArray = <Output, Def extends ZodTypeDef, Input>(
  3. schema: ZodSchema<Output, Def, Input>,
  4. ) =>
  5. z
  6. .array(schema)
  7. .length(1)
  8. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  9. .transform((value) => value[0]!);
  10. export const safeFetch = async <Output, Def extends ZodTypeDef, Input>(
  11. schema: ZodSchema<Output, Def, Input>,
  12. ...fetchArgs: Parameters<typeof fetch>
  13. ) => {
  14. const response = await fetch(...fetchArgs);
  15. const json: unknown = await response.json();
  16. return schema.parseAsync(json);
  17. };