Created
November 22, 2023 18:21
-
-
Save SandroMaglione/348afa5b5faf795214a6bf29f4c354f8 to your computer and use it in GitHub Desktop.
Helper functions to gradually migrate from `zod` to `@effect/schema`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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