Effect CommunityEC
Effect Community6mo ago
5 replies
SunRay

Creating a Database Service with Effect and Drizzle ORM in Next.js

Hi all, in my Next.js app, I am using drizzle ORM to talk to Supabase database.

Here is how the db/index.ts file looks like:

import { Effect, Config, Redacted } from "effect";
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";

const databaseUrl = Config.redacted("DATABASE_URL");

const connectionString = Redacted.value(Effect.runSync(databaseUrl));

// For Next.js edge runtime compatibility
const client = postgres(connectionString, {
  prepare: false,
  max: 5, // Connection pool size
});

export const db = drizzle(client);


And I am using the exported
db
like this:

export function getUserRole(email: string) {
  return Effect.gen(function* () {
    const result = yield* Effect.tryPromise({
      try: async () => {
        const result = await db
          .select({ role: usersTable.role })
          .from(usersTable)
          .where(eq(usersTable.email, email))
          .limit(1);

        return result;
      },
      catch: (error) =>
        new DatabaseError({
          operation: "getUserRole",
          cause: error,
        }),
    });

    if (result.length === 0) {
      yield* Effect.fail(new UserNotFoundError({ operation: "getUserRole" }));
    }

    return result[0].role;
  }).pipe(
    Effect.tapErrorTag("DatabaseError", (error) => Effect.logError(error)),
    Effect.tapErrorTag("UserNotFoundError", (error) => Effect.logError(error))
  );
}


I don't want to import the
db
to every function where I need to interact with the database, so I want to create a database Service using the Effect Service API.

While going through Effect's GitHub REDAME, I came across two packages:
@effect/sql
and
@effect/sql-drizzle
. Should I be using these packages to create the Service? What purpose do they solve? Anyone has got any code samples I can refer to?

I would appreciate if anyone can explain in simple words how these different pieces fit together. Thanks.
Was this page helpful?