run-service.test.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { expect } from "bun:test"
  2. import { Effect, Layer, Context } from "effect"
  3. import { makeRuntime } from "../../src/effect/run-service"
  4. import { it } from "../lib/effect"
  5. class Shared extends Context.Service<Shared, { readonly id: number }>()("@test/Shared") {}
  6. it.live("makeRuntime shares dependent layers through the shared memo map", () =>
  7. Effect.gen(function* () {
  8. let n = 0
  9. const shared = Layer.effect(
  10. Shared,
  11. Effect.sync(() => {
  12. n += 1
  13. return Shared.of({ id: n })
  14. }),
  15. )
  16. class One extends Context.Service<One, { readonly get: () => Effect.Effect<number> }>()("@test/One") {}
  17. const one = Layer.effect(
  18. One,
  19. Effect.gen(function* () {
  20. const svc = yield* Shared
  21. return One.of({
  22. get: Effect.fn("One.get")(() => Effect.succeed(svc.id)),
  23. })
  24. }),
  25. ).pipe(Layer.provide(shared))
  26. class Two extends Context.Service<Two, { readonly get: () => Effect.Effect<number> }>()("@test/Two") {}
  27. const two = Layer.effect(
  28. Two,
  29. Effect.gen(function* () {
  30. const svc = yield* Shared
  31. return Two.of({
  32. get: Effect.fn("Two.get")(() => Effect.succeed(svc.id)),
  33. })
  34. }),
  35. ).pipe(Layer.provide(shared))
  36. const { runPromise: runOne } = makeRuntime(One, one)
  37. const { runPromise: runTwo } = makeRuntime(Two, two)
  38. expect(yield* Effect.promise(() => runOne((svc) => svc.get()))).toBe(1)
  39. expect(yield* Effect.promise(() => runTwo((svc) => svc.get()))).toBe(1)
  40. expect(n).toBe(1)
  41. }),
  42. )