Creating a Reusable SurrealDB Service with Effect-TS

Hi everyone,

I'm new to effect-ts and trying to create a reusable service (Context.Tag) for managing my SurrealDB connection. The goal is to initialize this service and use it across different environments (e.g., server-side with Hono/SvelteKit, potentially client-side Svelte components - though I understand direct client DB access isn't standard).

I've managed to create an Effect using Effect.acquireRelease to handle the SurrealDB client connection lifecycle, based on some examples:

import { Effect, Context, Data } from 'effect';
import { Surreal, type ConnectOptions } from 'surrealdb.js'; // Or your specific import

// Error Type
export class SurrealDBError extends Data.TaggedError('SurrealDBError')<{
    cause?: unknown;
    message?: string;
}> {}

// Service Interface (Intended)
interface SurrealDBImpl {
    use: <T>(fn: (client: Surreal) => T) => Effect.Effect<Awaited<T>, SurrealDBError, never>;
}

// Service Tag
export class SurrealDB extends Context.Tag('SurrealDB')<SurrealDB, SurrealDBImpl>() {} // <-- Is this Tag definition correct?

// Function to manage connection lifecycle
export const makeConnectionEffect = (url: string | URL, options: ConnectOptions) =>
    Effect.acquireRelease(
        Effect.tryPromise({
            try: async () => {
                const _client = new Surreal();
                await _client.connect(url, options);
                // Add signin/use if needed
                return _client;
            },
            catch: (e) => new SurrealDBError({ cause: e, message: 'Error connecting' })
        }),
        (client) => Effect.promise(() => client.close()) // Or Effect.sync
    );

Thanks!
Was this page helpful?