Hyperlinkv0.8.0-beta.28

Context

Context.addconsteffect/Context.ts:685
<I, S>(key: Key<I, S>, service: Types.NoInfer<S>): <Services>(
  self: Context<Services>
) => Context<Services | I>
<Services, I, S>(
  self: Context<Services>,
  key: Key<I, S>,
  service: Types.NoInfer<S>
): Context<Services | I>

Adds a service to a given Context.

When to use

Use when you need to store a known service value in a Context.

Details

If the context already contains the same service key, the new service replaces the previous one.

Example (Adding a service to a context)

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

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

const someContext = Context.make(Port, { PORT: 8080 })

const context = pipe(
  someContext,
  Context.add(Timeout, { TIMEOUT: 5000 })
)

assert.deepStrictEqual(Context.get(context, Port), { PORT: 8080 })
assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 })
addersaddOrOmit
Source effect/Context.ts:68518 lines
export const add: {
  <I, S>(
    key: Key<I, S>,
    service: Types.NoInfer<S>
  ): <Services>(self: Context<Services>) => Context<Services | I>
  <Services, I, S>(
    self: Context<Services>,
    key: Key<I, S>,
    service: Types.NoInfer<S>
  ): Context<Services | I>
} = dual(3, <Services, I, S>(
  self: Context<Services>,
  key: Key<I, S>,
  service: Types.NoInfer<S>
): Context<Services | I> =>
  withMapUnsafe(self, (map) => {
    map.set(key.key, service)
  }))
Referenced by 7 symbols