Hyperlinkv0.8.0-beta.28

Context

Context.mergeAllconsteffect/Context.ts:1145
<T extends Array<unknown>>(
  ...ctxs: { [K in keyof T]: Context<T[K]> }
): Context<T[number]>

Merges any number of Contexts into one.

When to use

Use when you need to combine a variadic list of contexts.

Details

When multiple contexts contain the same service key, the service from the last context with that key is kept.

Example (Merging multiple contexts)

import { Context } from "effect"
import * as assert from "node:assert"

const Port = Context.Service<{ PORT: number }>("Port")
const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout")
const Host = Context.Service<{ HOST: string }>("Host")

const firstContext = Context.make(Port, { PORT: 8080 })
const secondContext = Context.make(Timeout, { TIMEOUT: 5000 })
const thirdContext = Context.make(Host, { HOST: "localhost" })

const context = Context.mergeAll(
  firstContext,
  secondContext,
  thirdContext
)

assert.deepStrictEqual(Context.get(context, Port), { PORT: 8080 })
assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 })
assert.deepStrictEqual(Context.get(context, Host), { HOST: "localhost" })
combiningmerge
Source effect/Context.ts:114511 lines
export const mergeAll = <T extends Array<unknown>>(
  ...ctxs: [...{ [K in keyof T]: Context<T[K]> }]
): Context<T[number]> => {
  const map = new Map()
  for (let i = 0; i < ctxs.length; i++) {
    ctxs[i].mapUnsafe.forEach((value, key) => {
      map.set(key, value)
    })
  }
  return makeUnsafe(map)
}
Referenced by 1 symbols