starfleet-ui
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#6 · main · 2 min 01 s
0Étoiles
0Forks
0Issues
| 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 | */ |
| 6 | import { invalidateAll } from '$app/navigation'; |
| 7 | import { callApi } from '$lib/api.client'; |
| 8 | import { specFor } from '$lib/game/actions'; |
| 9 | import { NO_DRY_RUN } from '$lib/game/errors'; |
| 10 | import { play } from '$lib/sound.svelte'; |
| 11 | import { toast } from '$lib/stores/toasts.svelte'; |
| 12 | import type { ApiErrorBody, GameAction } from '$lib/types'; |
| 13 | |
| 14 | /** Actions the API answered `no_dry_run` for during this session. */ |
| 15 | const refusedDryRun = new Set<string>(); |
| 16 | /** Money moves where a retry must not move credits twice. */ |
| 17 | const IDEMPOTENT = new Set(['deposit', 'withdraw']); |
| 18 | |
| 19 | export function canPreview(name: string): boolean { |
| 20 | return !specFor(name).noDryRun && !NO_DRY_RUN.has(name) && !refusedDryRun.has(name); |
| 21 | } |
| 22 | |
| 23 | export type RunResult = { ok: true; data: unknown; actions: GameAction[] } | { ok: false; error: ApiErrorBody }; |
| 24 | |
| 25 | export 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 | } |