Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

suggestions for effect plugin #3449

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 13 additions & 14 deletions plugin/effect/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import { Effect } from "effect";
import * as Effect from "effect/Effect";
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alias imports are better for library code, as they cause less issues with bundlers

import * as z from "zod";

function zodEffect(this: z.ZodType, data: unknown, params?: any) {
return Effect.tryPromise({
try: async () => this.parseAsync(data, params),
catch(error) {
return error as z.ZodError;
},
});
return Effect.flatMap(
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Effect.promise + flatMap allows us to use the safe apis

Effect.promise(() => this.safeParseAsync(data, params)),
(result) =>
result.success ? Effect.succeed(result.data) : Effect.fail(result.error)
);
}

function zodEffectSync(this: z.ZodType, data: unknown, params?: any) {
return Effect.try({
try: () => this.parse(data, params),
catch(error) {
return error as z.ZodError;
},
return Effect.suspend(() => {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Effect.suspend allows us to wrap a side effect that returns an Effect, perfect for the sync api.

const result = this.safeParse(data, params);
return result.success
? Effect.succeed(result.data)
: Effect.fail(result.error);
});
}

Expand All @@ -31,10 +30,10 @@ declare module "zod" {
interface ZodType {
effect(
...args: Parameters<z.ZodType["parseAsync"]>
): Effect.Effect<this["_output"], z.ZodError<this["_output"]>, never>;
): Effect.Effect<this["_output"], z.ZodError<this["_output"]>>;
effectSync(
...args: Parameters<z.ZodType["parse"]>
): Effect.Effect<this["_output"], z.ZodError<this["_output"]>, never>;
): Effect.Effect<this["_output"], z.ZodError<this["_output"]>>;
}

interface ZodError {
Expand Down