Effect CommunityEC
Effect Community3y ago
7 replies
matias

Understanding the Effect Library and Refactoring Async/Await Functions

Hey there!.
I'm just starting to dig into the Effect library and I'm struggling to make my head around, I hope you can help me with the very first steps.
First of all, what I want is to refactor a (long) piece of code that I have that is basically a cascade of async/await functions that manipulate some data and trigger some "effects"

Each of the function returns something like this Promise<[TData, null] | [null, TError]>

the main function looks like this

export async function main(event: SQSEvent) {
    const records: SQSRecord[] = event.Records;
    if (records.length > 0) {
        records.forEach(async (record) => {
            const [data, parseError] = parseRecord(record)
            if (data == null) {
                console.error(parseError)
                return false
            }
            const [canContinue, retryError] = await checkJobRetryCount({ userId: data.userId, jobId: data.jobId })
            if (!canContinue) {
                console.error(retryError)
                return false
            }
            return true
        });
    }

    return {};
}


I want to refactor that to use effect.
My first step was to refactor the first function there, that is just a wrapper to zod, so will return Effect.succeed or Effect.fail

then refactor the next async functon that return a Promise and here is where I went blocked.

Should I use Effect.tryCatchPromise to run each part of that functon and then the main function will become something like

const process = pipe(
    record,
    parseRecord,
    Effect.flatMap(checkJobRetryCount)
Effect.flaMap(nextFunction)
)

Am I right?
And to share "context" across this functions I should use the Context part of the Effect?

thanks
Was this page helpful?