25 lines · 774 B
import { env } from "cloudflare:workers";
import type { CounterKind, Totals } from "./counters-do";

function counters(kind: CounterKind, scope: string) {
  return env.COUNTERS.get(env.COUNTERS.idFromName(`${kind}:${scope}`));
}

export function addCounter(
  kind: CounterKind,
  scope: string,
  key: string,
  delta: Totals,
  meta: string | null = null,
): Promise<Totals> {
  return counters(kind, scope)
    .add(kind, scope, key, delta, meta)
    .then((totals): Totals => [totals[0] ?? 0, totals[1] ?? 0, totals[2] ?? 0]);
}

export function counterTotals(kind: CounterKind, scope: string, key: string): Promise<Totals> {
  return counters(kind, scope)
    .totals(kind, scope, key)
    .then((totals): Totals => [totals[0] ?? 0, totals[1] ?? 0, totals[2] ?? 0]);
}