Effect CommunityEC
Effect Community9mo ago
7 replies
Desch

Help learning fn composability

Hey all! I'm just starting learning Effect. I know JavaScript and TypeScript very well.

I think this question is fairly basic, but I'm looking for some guidance on how to think about breaking down functions into Effect fn's and how to tie them together. I've read the docs, but they focus mostly on one function definition and then a top level execution instead of multiple functions tied together.

What I'm trying to do is call a third party API, and if an error occurs I want to return a custom error type with the error message. My understanding is this should be broken into two steps; one Effect that wraps the API call, and another that converts the error message into the appropriate error.

First up, the error type I want to throw since it has no dependencies:

export class ApiDataError extends Data.TaggedError("ApiDataError")<{
    message: string;
}> {}


I believe I want to use tryPromise for the API call. My implementation looks like this:

const getData = Effect.fn("getData")(function* <T>(key: string) {
    Effect.tryPromise({
        try: () => get<T>(key),
        catch: (error) => ...
        });
});


(skipping schema validations)

Since error is an unknown type, I want to convert it into a string I can use as the arg: { message } param in my error. That function is also straightforward:

export const getErrorMessage = Effect.fn("getErrorMessage")(function* (
    error: unknown
) {
    if (error instanceof Error) {
        return Effect.succeed(error.message);
    }

    if (typeof error === "string") {
        return Effect.succeed(error);
    }

    if (typeof error === "object" && error !== null) {
        const message = (error as { message?: string }).message;
        if (typeof message === "string") {
            return Effect.succeed(message);
        }
    }

    return Effect.succeed("Unknown error");
});


Where I get confused is how do I tie these pieces together in the catch: (error) => {} handler?
Was this page helpful?