Skip to content

Commit

Permalink
Db - add layer constructors for DbService
Browse files Browse the repository at this point in the history
  • Loading branch information
VenomAV committed Sep 27, 2024
1 parent de2cdf8 commit 0651900
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/Db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -24,3 +26,29 @@ export type DbService<K extends string> = {
} & Brand.Brand<K>

export const Tag = <K extends string>(key: K) => Context.GenericTag<DbService<K>>(key)
export type TagType<K extends string> = ReturnType<typeof Tag<K>>

export const fromEffect = <DbK extends string, MongoClientK extends string, E = never, R = never>(
dbTag: TagType<DbK>,
clientTag: MongoClient.TagType<MongoClientK>,
dbName: Effect.Effect<string, E, R>
) =>
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<DbK>) // TODO fix cast using branded ctor
})
)

export const fromConst = <DbK extends string, MongoClientK extends string>(
dbTag: TagType<DbK>,
clientTag: MongoClient.TagType<MongoClientK>,
dbName: string
) => fromEffect(dbTag, clientTag, Effect.succeed(dbName))
1 change: 1 addition & 0 deletions src/MongoClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ export type MongoClientService<K extends string> = {
} & Brand.Brand<K>

export const Tag = <K extends string>(key: K) => Context.GenericTag<MongoClientService<K>>(key)
export type TagType<K extends string> = ReturnType<typeof Tag<K>>

0 comments on commit 0651900

Please sign in to comment.