Hyperlinkv0.8.0-beta.28

Cache

Cache.makeWithconsteffect/Cache.ts:177
<
  Key,
  A,
  E = never,
  R = never,
  ServiceMode extends "lookup" | "construction" = never
>(
  lookup: (key: Key) => Effect.Effect<A, E, R>,
  options: {
    readonly capacity: number
    readonly timeToLive?:
      | ((exit: Exit.Exit<A, E>, key: Key) => Duration.Input)
      | undefined
    readonly requireServicesAt?: ServiceMode | undefined
  }
): Effect.Effect<
  Cache<Key, A, E, "lookup" extends ServiceMode ? R : never>,
  never,
  "lookup" extends ServiceMode ? never : R
>

Creates a cache with dynamic time-to-live based on the result and key.

When to use

Use when you need different cache entry lifetimes based on the lookup result or key characteristics.

Details

The timeToLive function receives both the exit result and the key, allowing for flexible TTL policies based on success/failure state and key characteristics.

Example (Configuring dynamic time to live)

import { Cache, Effect, Exit } from "effect"

// Cache with TTL based on computed value
const userCache = Effect.gen(function*() {
  const cache = yield* Cache.makeWith(
    (id: number) => Effect.succeed({ id, active: id % 2 === 0 }),
    {
      capacity: 1000,
      timeToLive(exit) {
        if (Exit.isSuccess(exit)) {
          const user = exit.value
          return user.active ? "1 hour" : "5 minutes"
        }
        return "30 seconds"
      }
    }
  )

  return cache
})
constructorsmake
Source effect/Cache.ts:17729 lines
export const makeWith = <
  Key,
  A,
  E = never,
  R = never,
  ServiceMode extends "lookup" | "construction" = never
>(lookup: (key: Key) => Effect.Effect<A, E, R>, options: {
  readonly capacity: number
  readonly timeToLive?: ((exit: Exit.Exit<A, E>, key: Key) => Duration.Input) | undefined
  readonly requireServicesAt?: ServiceMode | undefined
}): Effect.Effect<
  Cache<Key, A, E, "lookup" extends ServiceMode ? R : never>,
  never,
  "lookup" extends ServiceMode ? never : R
> =>
  effect.contextWith((context: Context.Context<any>) => {
    const self = Object.create(Proto)
    self.lookup = (key: Key): Effect.Effect<A, E> =>
      effect.updateContext(
        lookup(key),
        (input) => Context.merge(context, input)
      )
    self.map = MutableHashMap.make()
    self.capacity = options.capacity
    self.timeToLive = options.timeToLive
      ? (exit: Exit.Exit<A, E>, key: Key) => Duration.fromInputUnsafe(options.timeToLive!(exit, key))
      : defaultTimeToLive
    return effect.succeed(self as Cache<Key, A, E>)
  })
Referenced by 2 symbols