| 1 | /** |
| 2 | * @title Composing services with the Layer module |
| 3 | * |
| 4 | * Build focused service layers, then compose them with `Layer.provide` and |
| 5 | * `Layer.provideMerge` based on what services you want to expose. |
| 6 | */ |
| 7 | |
| 8 | import { PgClient } from "@effect/sql-pg" |
| 9 | import { Array, Config, Context, Effect, Layer, type Option, Schema } from "effect" |
| 10 | import { SqlClient, SqlError } from "effect/sql" |
| 11 | |
| 12 | // Define a layer for the SqlClient service |
| 13 | export const SqlClientLayer: Layer.Layer< |
| 14 | PgClient.PgClient | SqlClient.SqlClient, |
| 15 | Config.ConfigError | SqlError.SqlError |
| 16 | > = PgClient.layerConfig({ |
| 17 | url: Config.Redacted("DATABASE_URL") |
| 18 | }) |
| 19 | |
| 20 | export class UserRespositoryError extends Schema.TaggedError<UserRespositoryError>()("UserRespositoryError", { |
| 21 | reason: SqlError.SqlError |
| 22 | }) {} |
| 23 | |
| 24 | export class UserRepository extends Context.Service<UserRepository, { |
| 25 | findById(id: string): Effect.Effect< |
| 26 | Option.Option<{ readonly id: string; readonly name: string }>, |
| 27 | UserRespositoryError |
| 28 | > |
| 29 | }>()("myapp/UserRepository") { |
| 30 | // Implement the layer for the UserRepository service, which depends on the |
| 31 | // SqlClient service |
| 32 | static readonly layerNoDeps: Layer.Layer< |
| 33 | UserRepository, |
| 34 | never, |
| 35 | SqlClient.SqlClient |
| 36 | > = Layer.effect( |
| 37 | UserRepository, |
| 38 | Effect.gen(function*() { |
| 39 | const sql = yield* SqlClient.SqlClient |
| 40 | |
| 41 | const findById = Effect.fn("UserRepository.findById")(function*(id: string) { |
| 42 | const results = yield* sql<{ |
| 43 | readonly id: string |
| 44 | readonly name: string |
| 45 | }>`SELECT * FROM users WHERE id = '${id}'` |
| 46 | return Array.head(results) |
| 47 | }, Effect.mapError((reason) => new UserRespositoryError({ reason }))) |
| 48 | |
| 49 | return UserRepository.of({ findById }) |
| 50 | }) |
| 51 | ) |
| 52 | |
| 53 | // Use Layer.provide to compose the UserRepository layer with the SqlClient |
| 54 | // layer, exposing only the UserRepository service |
| 55 | static readonly layer: Layer.Layer< |
| 56 | UserRepository, |
| 57 | Config.ConfigError | SqlError.SqlError |
| 58 | > = this.layerNoDeps.pipe( |
| 59 | Layer.provide(SqlClientLayer) |
| 60 | ) |
| 61 | |
| 62 | // Use Layer.provideMerge to compose the UserRepository layer with the SqlClient |
| 63 | // layer, exposing both the UserRepository and SqlClient services |
| 64 | static readonly layerWithSqlClient: Layer.Layer< |
| 65 | UserRepository | SqlClient.SqlClient, |
| 66 | Config.ConfigError | SqlError.SqlError |
| 67 | > = this.layerNoDeps.pipe( |
| 68 | Layer.provideMerge(SqlClientLayer) |
| 69 | ) |
| 70 | } |