Hyperlinkv0.8.0-beta.28

LayerMap

LayerMap.makeconsteffect/LayerMap.ts:135
<
  K,
  L extends Layer.Layer<any, any, any>,
  PreloadKeys extends Iterable<K> | undefined = undefined
>(
  lookup: (key: K) => L,
  options?:
    | {
        readonly idleTimeToLive?: IdleTimeToLiveInput<K> | undefined
        readonly preloadKeys?: PreloadKeys
      }
    | undefined
): Effect.Effect<
  LayerMap<K, Layer.Success<L>, Layer.Error<L>>,
  PreloadKeys extends undefined ? never : Layer.Error<L>,
  Scope.Scope | Layer.Services<L>
>

Creates a LayerMap that dynamically provides resources based on a key.

Example (Creating a layer map)

import { Context, Effect, Layer, LayerMap } from "effect"

// Define a service key
const DatabaseService = Context.Service<{
  readonly query: (sql: string) => Effect.Effect<string>
}>("Database")

// Create a LayerMap that provides different database configurations
const program = Effect.gen(function*() {
  const layerMap = yield* LayerMap.make(
    (env: string) =>
      Layer.succeed(DatabaseService)({
        query: Effect.fn("DatabaseService.query")((sql) => Effect.succeed(`${env}: ${sql}`))
      }),
    { idleTimeToLive: "5 seconds" }
  )

  // Get a layer for a specific environment
  const devLayer = layerMap.get("development")

  // Use the layer to provide the service
  const result = yield* Effect.provide(
    Effect.gen(function*() {
      const db = yield* DatabaseService
      return yield* db.query("SELECT * FROM users")
    }),
    devLayer
  )

  console.log(result) // "development: SELECT * FROM users"
})
constructors
Source effect/LayerMap.ts:13539 lines
export const make: <
  K,
  L extends Layer.Layer<any, any, any>,
  PreloadKeys extends Iterable<K> | undefined = undefined
>(
  lookup: (key: K) => L,
  options?: {
    readonly idleTimeToLive?: IdleTimeToLiveInput<K> | undefined
    readonly preloadKeys?: PreloadKeys
  } | undefined
) => Effect.Effect<
  LayerMap<K, Layer.Success<L>, Layer.Error<L>>,
  PreloadKeys extends undefined ? never : Layer.Error<L>,
  Scope.Scope | Layer.Services<L>
> = Effect.fnUntraced(function*<I, K, EL, RL>(
  lookup: (key: K) => Layer.Layer<I, EL, RL>,
  options?: {
    readonly idleTimeToLive?: IdleTimeToLiveInput<K> | undefined
  } | undefined
) {
  const context = yield* Effect.context<never>()
  const memoMap = Layer.CurrentMemoMap.forkOrCreate(context)

  const rcMap = yield* RcMap.make({
    lookup: (key: K) =>
      Effect.contextWith((_: Context.Context<Scope.Scope>) =>
        Layer.buildWithMemoMap(lookup(key), memoMap, Context.get(_, Scope.Scope))
      ),
    idleTimeToLive: options?.idleTimeToLive
  })

  return identity<LayerMap<K, I, any>>({
    [TypeId]: TypeId,
    rcMap,
    get: (key) => Layer.effectContext(RcMap.get(rcMap, key)),
    contextEffect: (key) => RcMap.get(rcMap, key),
    invalidate: (key) => RcMap.invalidate(rcMap, key)
  })
})
Referenced by 2 symbols