Implement a Counter Service with Ref in Effect-TS

Hello, I am now exploring how services and ref works, in my cli app I have four let variables that are counters, I pass them around and increment them. using 4 separate Service is working but I would like to condense them in a single service with a get and a inc(counterName) but I dont understand on how to do it. So far I did this but it does not work
import { Context, Effect, Layer, Ref } from "effect";

type state = {
    count: number;
    error_count: number;
    processed: number;
    skipped: number;
};

interface CounterStateI {
    readonly inc: (counter: keyof state) => Effect.Effect<void>;
    get: Effect.Effect<state>;
}

export class CounterState extends Context.Tag("CounterState")<
    CounterState,
    CounterStateI
>() {}

export const initialState = Ref.make({
    count: 0,
    error_count: 0,
    processed: 0,
    skipped: 0,
});

class CounterStateImpl implements CounterStateI {
    #value: Ref.Ref<state>;

    constructor(value: Ref.Ref<state>) {
        this.#value = value;
        this.get = Ref.get(this.#value);
    }

    inc(counter: keyof state) {
        this.#value;
        return Ref.update(this.#value, (old_state) => {
            const new_state = { ...old_state };
            new_state[counter] = old_state[counter] + 1;
            return new_state;
        });
    }
    get = Ref.get(this.#value);
}

export const CounterStateLive = Layer.succeed(
    CounterState,
    CounterState.of(new CounterStateImpl(initialState)),
);
Was this page helpful?