Effect CommunityEC
Effect Community17mo ago
3 replies
araera111

Ensuring DB Connection Closure in Effect on Success and Failure

Hello,

I am working with Effect and using a MySQL database service. I want to ensure that the database connection is properly closed using await con.end() whether the Effect succeeds or fails. Could you advise on the best approach to accomplish this?

For reference, I have been experimenting with the following example using mysql2:

import { Context, Effect } from "effect";
import { type Connection, createConnection } from "mysql2/promise";

class mysql2Con extends Context.Tag("mysql2")<
    mysql2Con,
    { readonly con: Effect.Effect<Connection> }
>() {}

type QueryEffectProps = {
    con: Connection;
    query: string;
};
const queryEffect = ({ con, query }: QueryEffectProps) =>
    Effect.tryPromise({
        try: () => con.query(query),
        catch: (e) => props: ${query} ${e},
    });

// not working query
const errorQuery =
    "SELECT * FROM my_table LIMIT 1 ORDER BY updated_at DESC";

const program2 = mysql2Con.pipe(
    Effect.andThen((mysql2) => mysql2.con),
    Effect.bindTo("con"),
    Effect.bind("query", ({ con }) => queryEffect({ con, query: errorQuery })),
);
const runnable2 = Effect.provideService(program2, mysql2Con, {
    con: Effect.promise(() =>
        // your mysql connection
        createConnection({
            host: "example.com",
            database: "example",
            user: "example_user",
            port: 3306,
            password: "example_password",
        }),
    ),
});

Effect.runPromiseExit(runnable2).then(async (exit) => {
        //??? where await con.end() ??? 
    if (exit._tag === "Success") {
        console.log("Success", exit.value.query);
    }
    console.log("Error", exit);
    throw new Error("Error");
});


Thank you for your assistance.

Best regards,
Yuumillar
Was this page helpful?