Providing Transaction Context for Specific Scope

I'm trying to convert Drizzle with Effect TS.

something like:
db.transaction(tx => {
  const todoRepository = new TodoRepository(tx);
  return todoRepository.getById(...)
});


into
Effect.runPromise(
  pipe(
    WithTransaction.pipe(
      TodoRepository,
      Effect.map(todoRepository => todoRepository.getById(...)
    ),
    Effect.provideService(DatabaseService, ...),
  ),
);


I want to create transaction scope for the pipe, and then release transaction automatically.
perhaps, it needs composing both Layer.scopedContext or Runtime/Fiber?
I would be helpful if you give me a hint or clue.

My last attempt was:

const WithTransaction = Layer.scopedContext(
  pipe(
    DatabaseService,
    Effect.flatMap((database) => {
      const { promise, resolve } = Promise.withResolvers();
      return Effect.acquireRelease(
        Effect.sync(() => {
          let _transaction: Database;
          database.transaction((transaction) => {
            _transaction = transaction;
            return promise;
          });
          return _transaction!;
        }),
        () => Effect.sync(() => resolve()),
      );
    }),
  ),
);
Was this page helpful?