From 53d7e1770c693ca964df9bf4f6d45a10038a8ed2 Mon Sep 17 00:00:00 2001 From: Asger Geel Weirsoee Date: Sun, 1 Mar 2026 12:45:32 +0000 Subject: [PATCH] feat(spa): wire join/start round in Angular API client for lobby flow --- frontend/src/api/angular-client.ts | 97 +++++++++++++++ frontend/tests/angular-api-client.test.ts | 141 ++++++++++++++++++++++ 2 files changed, 238 insertions(+) create mode 100644 frontend/src/api/angular-client.ts create mode 100644 frontend/tests/angular-api-client.test.ts diff --git a/frontend/src/api/angular-client.ts b/frontend/src/api/angular-client.ts new file mode 100644 index 0000000..6befb53 --- /dev/null +++ b/frontend/src/api/angular-client.ts @@ -0,0 +1,97 @@ +import type { + ApiFailure, + ApiResult, + HealthResponse, + JoinSessionRequest, + JoinSessionResponse, + SessionDetailResponse, + StartRoundRequest, + StartRoundResponse +} from './types'; + +export interface AngularHttpError { + status?: number; + message?: string; + error?: unknown; +} + +export interface AngularHttpClientLike { + get(url: string, options?: { withCredentials?: boolean }): Promise; + post(url: string, body: unknown, options?: { withCredentials?: boolean }): Promise; +} + +export interface AngularApiClient { + health(): Promise>; + getSession(code: string): Promise>; + joinSession(payload: JoinSessionRequest): Promise>; + startRound(code: string, payload: StartRoundRequest): Promise>; +} + +function toFailure(error: unknown): ApiFailure { + const candidate = (error ?? {}) as AngularHttpError; + const status = typeof candidate.status === 'number' ? candidate.status : 0; + const payload = candidate.error; + + if (status === 0) { + return { + kind: 'network', + status: 0, + message: candidate.message ?? 'Network error while contacting API' + }; + } + + return { + kind: 'http', + status, + message: candidate.message ?? `HTTP ${status}`, + ...(payload === undefined ? {} : { payload }) + }; +} + +function normalizeCode(code: string): string { + return code.trim().toUpperCase(); +} + +async function wrap(call: () => Promise): Promise> { + try { + const data = await call(); + return { ok: true, status: 200, data }; + } catch (error: unknown) { + return { + ok: false, + status: typeof (error as AngularHttpError)?.status === 'number' ? (error as AngularHttpError).status! : 0, + error: toFailure(error) + }; + } +} + +export function createAngularApiClient(http: AngularHttpClientLike, baseUrl = ''): AngularApiClient { + return { + health: () => wrap(() => http.get(`${baseUrl}/healthz`, { withCredentials: true })), + getSession: (code: string) => + wrap(() => + http.get(`${baseUrl}/lobby/sessions/${encodeURIComponent(normalizeCode(code))}`, { + withCredentials: true + }) + ), + joinSession: (payload: JoinSessionRequest) => + wrap(() => + http.post( + `${baseUrl}/lobby/sessions/join`, + { + code: normalizeCode(payload.code), + nickname: payload.nickname.trim() + }, + { withCredentials: true } + ) + ), + startRound: (code: string, payload: StartRoundRequest) => + wrap(() => + http.post( + `${baseUrl}/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/rounds/start`, + payload, + { withCredentials: true } + ) + ) + }; +} diff --git a/frontend/tests/angular-api-client.test.ts b/frontend/tests/angular-api-client.test.ts new file mode 100644 index 0000000..1cc7fc7 --- /dev/null +++ b/frontend/tests/angular-api-client.test.ts @@ -0,0 +1,141 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { createAngularApiClient, type AngularHttpClientLike } from '../src/api/angular-client'; + +describe('createAngularApiClient', () => { + it('reads health and session detail using Django-compatible endpoints', async () => { + const get = vi.fn(async (url: string) => { + if (url === '/healthz') { + return { ok: true, service: 'partyhub' } as T; + } + + if (url === '/lobby/sessions/ABCD12') { + return { + session: { code: 'ABCD12', status: 'lobby', host_id: 1, current_round: 1, players_count: 2 }, + players: [ + { id: 2, nickname: 'Maja', score: 0, is_connected: true }, + { id: 3, nickname: 'Bo', score: 0, is_connected: false } + ], + round_question: null, + phase_view_model: { + status: 'lobby', + round_number: 1, + players_count: 2, + constraints: { + min_players_to_start: 2, + max_players_mvp: 8, + min_players_reached: true, + max_players_allowed: true + }, + host: { + can_start_round: true, + can_show_question: false, + can_mix_answers: false, + can_calculate_scores: false, + can_reveal_scoreboard: false, + can_start_next_round: false, + can_finish_game: false + }, + player: { + can_join: true, + can_submit_lie: false, + can_submit_guess: false, + can_view_final_result: false + } + } + } as T; + } + + throw { status: 404, error: { error: 'Not found' } }; + }); + + const post = vi.fn(async (url: string, body: unknown) => { + if (url === '/lobby/sessions/join') { + expect(body).toEqual({ code: 'ABCD12', nickname: 'Maja' }); + return { + player: { id: 9, nickname: 'Maja', session_token: 'token-1', score: 0 }, + session: { code: 'ABCD12', status: 'lobby' } + } as T; + } + + if (url === '/lobby/sessions/ABCD12/rounds/start') { + expect(body).toEqual({ category_slug: 'history' }); + return { + session: { code: 'ABCD12', status: 'lie', current_round: 1 }, + round: { number: 1, category: { slug: 'history', name: 'History' } } + } as T; + } + + throw { status: 404, error: { error: 'Not found' } }; + }); + + const http = { get, post }; + const client = createAngularApiClient(http as AngularHttpClientLike); + + const health = await client.health(); + expect(health.ok).toBe(true); + if (health.ok) { + expect(health.data.ok).toBe(true); + expect(health.data.service).toBe('partyhub'); + } + + const session = await client.getSession(' abcd12 '); + expect(session.ok).toBe(true); + if (session.ok) { + expect(session.data.session.code).toBe('ABCD12'); + expect(session.data.session.host_id).toBe(1); + expect(session.data.phase_view_model.host.can_start_round).toBe(true); + } + + const join = await client.joinSession({ code: ' abcd12 ', nickname: ' Maja ' }); + expect(join.ok).toBe(true); + + const start = await client.startRound(' abcd12 ', { category_slug: 'history' }); + expect(start.ok).toBe(true); + + expect(get).toHaveBeenNthCalledWith(1, '/healthz', { withCredentials: true }); + expect(get).toHaveBeenNthCalledWith(2, '/lobby/sessions/ABCD12', { withCredentials: true }); + expect(post).toHaveBeenNthCalledWith( + 1, + '/lobby/sessions/join', + { code: 'ABCD12', nickname: 'Maja' }, + { withCredentials: true } + ); + expect(post).toHaveBeenNthCalledWith( + 2, + '/lobby/sessions/ABCD12/rounds/start', + { category_slug: 'history' }, + { withCredentials: true } + ); + }); + + it('maps HttpErrorResponse-style failures to ApiResult errors', async () => { + const http = { + get: vi.fn(async () => { + throw { status: 503, message: 'Service unavailable', error: { error: 'maintenance' } }; + }), + post: vi.fn(async () => { + throw { status: 403, message: 'Forbidden', error: { error: 'Only host can start round' } }; + }) + }; + + const client = createAngularApiClient(http as AngularHttpClientLike); + const health = await client.health(); + + expect(health.ok).toBe(false); + if (!health.ok) { + expect(health.status).toBe(503); + expect(health.error.kind).toBe('http'); + expect(health.error.payload).toEqual({ error: 'maintenance' }); + expect(health.error.message).toContain('Service unavailable'); + } + + const start = await client.startRound('ABCD12', { category_slug: 'history' }); + expect(start.ok).toBe(false); + if (!start.ok) { + expect(start.status).toBe(403); + expect(start.error.kind).toBe('http'); + expect(start.error.payload).toEqual({ error: 'Only host can start round' }); + } + }); +});