tobogganSe connecter

starfleet-ui

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

45 lignes · 1735 octetsBrut · Historique
1/**
2 * Runs an API action from the UI: one place for dry-run rules, idempotency keys,
3 * sounds, success toasts and refreshing page data. Errors are returned (not toasted)
4 * so the caller can show them next to the field or offer a fix.
5 */
6import { invalidateAll } from '$app/navigation';
7import { callApi } from '$lib/api.client';
8import { specFor } from '$lib/game/actions';
9import { NO_DRY_RUN } from '$lib/game/errors';
10import { play } from '$lib/sound.svelte';
11import { toast } from '$lib/stores/toasts.svelte';
12import type { ApiErrorBody, GameAction } from '$lib/types';
13
14/** Actions the API answered `no_dry_run` for during this session. */
15const refusedDryRun = new Set<string>();
16/** Money moves where a retry must not move credits twice. */
17const IDEMPOTENT = new Set(['deposit', 'withdraw']);
18
19export function canPreview(name: string): boolean {
20 return !specFor(name).noDryRun && !NO_DRY_RUN.has(name) && !refusedDryRun.has(name);
21}
22
23export type RunResult = { ok: true; data: unknown; actions: GameAction[] } | { ok: false; error: ApiErrorBody };
24
25export async function runAction(
26 action: GameAction,
27 body: Record<string, unknown> | undefined,
28 { dryRun = false }: { dryRun?: boolean } = {}
29): Promise<RunResult> {
30 const res = await callApi(action.method, action.href, body, {
31 dryRun,
32 idempotencyKey: IDEMPOTENT.has(action.name) ? crypto.randomUUID() : undefined
33 });
34 if (!res.ok) {
35 if (res.error.code === 'no_dry_run') refusedDryRun.add(action.name);
36 if (!dryRun) play('error');
37 return res;
38 }
39 if (!dryRun) {
40 play('confirm');
41 toast(`${specFor(action).label} — done.`, 'success', 3500);
42 await invalidateAll();
43 }
44 return { ok: true, data: res.envelope.data, actions: res.envelope.actions ?? [] };
45}