Skip to content

Instantly share code, notes, and snippets.

@SandroMaglione
Created November 22, 2023 18:21
Show Gist options
  • Save SandroMaglione/348afa5b5faf795214a6bf29f4c354f8 to your computer and use it in GitHub Desktop.
Save SandroMaglione/348afa5b5faf795214a6bf29f4c354f8 to your computer and use it in GitHub Desktop.
Helper functions to gradually migrate from `zod` to `@effect/schema`
import { Data, Either } from "effect";
import type { z } from "zod";
export class ZodParseError<In> extends Data.TaggedError("ZodParseError")<{
error: z.ZodError<In>;
}> {}
export const parseZod =
<ReqOut, ReqIn>(schema: z.Schema<ReqOut, z.ZodTypeDef, ReqIn>) =>
<T>(data: T): Either.Either<ZodParseError<ReqIn>, ReqOut> => {
const parsed = schema.safeParse(data);
return parsed.success
? Either.right(parsed.data)
: Either.left(new ZodParseError({ error: parsed.error }));
};
export const parseBrandZod =
<A extends z.ZodTypeAny, B extends string | number | symbol>(
schema: z.ZodBranded<A, B>
) =>
<T>(
data: T
): Either.Either<ZodParseError<A["_input"]>, A["_output"] & z.BRAND<B>> => {
const parsed = schema.safeParse(data);
return parsed.success
? Either.right(parsed.data)
: Either.left(new ZodParseError({ error: parsed.error }));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment