| 1 | import { Array as Arr, Context, Effect, Layer, Ref } from "effect" |
| 2 | |
| 3 | export interface TestAction { |
| 4 | readonly command: string |
| 5 | readonly details: Record<string, unknown> |
| 6 | } |
| 7 | |
| 8 | export class TestActions extends Context.Service<TestActions, { |
| 9 | readonly log: (action: TestAction) => Effect.Effect<void> |
| 10 | readonly getActions: Effect.Effect<ReadonlyArray<TestAction>> |
| 11 | }>()("TestActions") {} |
| 12 | |
| 13 | const make = Effect.gen(function*() { |
| 14 | const actions = yield* Ref.make<ReadonlyArray<TestAction>>([]) |
| 15 | return TestActions.of({ |
| 16 | getActions: Ref.get(actions), |
| 17 | log: (action) => Ref.update(actions, Arr.append(action)) |
| 18 | }) |
| 19 | }) |
| 20 | |
| 21 | export const layer = Layer.effect(TestActions, make) |
| 22 | |
| 23 | export const logAction = ( |
| 24 | command: string, |
| 25 | details: Record<string, unknown> = {} |
| 26 | ): Effect.Effect<void, never, TestActions> => |
| 27 | Effect.flatMap( |
| 28 | TestActions, |
| 29 | (actions) => actions.log({ command, details }) |
| 30 | ) |
| 31 | |
| 32 | export const getActions: Effect.Effect< |
| 33 | ReadonlyArray<TestAction>, |
| 34 | never, |
| 35 | TestActions |
| 36 | > = Effect.flatMap(TestActions, (actions) => actions.getActions) |