From 0651900fa604df234ac5b65cd839773d930eef39 Mon Sep 17 00:00:00 2001 From: Andrea Vallotti Date: Fri, 27 Sep 2024 18:01:47 +0200 Subject: [PATCH] Db - add layer constructors for DbService --- src/Db.ts | 28 ++++++++++++++++++++++++++++ src/MongoClient.ts | 1 + 2 files changed, 29 insertions(+) diff --git a/src/Db.ts b/src/Db.ts index 7c9c8cb..8e7617c 100644 --- a/src/Db.ts +++ b/src/Db.ts @@ -5,8 +5,10 @@ import type * as Brand from "effect/Brand" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as F from "effect/Function" +import * as Layer from "effect/Layer" import type { Db } from "mongodb" import * as DocumentCollection from "./DocumentCollection.js" +import * as MongoClient from "./MongoClient.js" import type * as MongoError from "./MongoError.js" export const collection: { @@ -24,3 +26,29 @@ export type DbService = { } & Brand.Brand export const Tag = (key: K) => Context.GenericTag>(key) +export type TagType = ReturnType> + +export const fromEffect = ( + dbTag: TagType, + clientTag: MongoClient.TagType, + dbName: Effect.Effect +) => + Layer.effect( + dbTag, + Effect.gen(function*(_) { + const { client } = yield* _(clientTag) + const dbName_ = yield* _(dbName) + const db = yield* _( + client, + Effect.flatMap((client) => MongoClient.db(client, dbName_)), + Effect.cached + ) + return dbTag.of({ db } as DbService) // TODO fix cast using branded ctor + }) + ) + +export const fromConst = ( + dbTag: TagType, + clientTag: MongoClient.TagType, + dbName: string +) => fromEffect(dbTag, clientTag, Effect.succeed(dbName)) diff --git a/src/MongoClient.ts b/src/MongoClient.ts index 862d328..4d2fa8a 100644 --- a/src/MongoClient.ts +++ b/src/MongoClient.ts @@ -30,3 +30,4 @@ export type MongoClientService = { } & Brand.Brand export const Tag = (key: K) => Context.GenericTag>(key) +export type TagType = ReturnType>