api.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import type { DailyResponse } from '@wordle/shared';
  2. import { getApiBase } from './messages/index.js';
  3. function base() { return getApiBase(); }
  4. async function fetchJSON<T>(url: string, options?: RequestInit): Promise<T> {
  5. const res = await fetch(url, options);
  6. if (!res.ok) {
  7. const body = await res.json().catch(() => ({}));
  8. throw new Error((body as { error?: string }).error ?? `HTTP ${res.status}`);
  9. }
  10. return res.json() as Promise<T>;
  11. }
  12. export function getValidateWord(word: string): Promise<{ word: string; valid: boolean }> {
  13. return fetchJSON(`${base()}/validate/${encodeURIComponent(word)}`);
  14. }
  15. export function getDaily(): Promise<DailyResponse> {
  16. return fetchJSON<DailyResponse>(`${base()}/daily`);
  17. }
  18. export function postGuess(body: { wordId: number; guess: string; tryNo: number }): Promise<import('@wordle/shared').GuessResponse> {
  19. return fetchJSON(`${base()}/guess`, {
  20. method: 'POST',
  21. headers: { 'Content-Type': 'application/json' },
  22. body: JSON.stringify(body),
  23. });
  24. }
  25. export function postPlayAgain(body: { skillMetric: number }): Promise<import('@wordle/shared').PlayAgainResponse> {
  26. return fetchJSON(`${base()}/play-again`, {
  27. method: 'POST',
  28. headers: { 'Content-Type': 'application/json' },
  29. body: JSON.stringify(body),
  30. });
  31. }
  32. export function postSolver(body: import('@wordle/shared').SolverRequest): Promise<import('@wordle/shared').SolverResponse> {
  33. return fetchJSON(`${base()}/solver`, {
  34. method: 'POST',
  35. headers: { 'Content-Type': 'application/json' },
  36. body: JSON.stringify(body),
  37. });
  38. }