feat(spa): wire join/start round in Angular API client for lobby flow

This commit is contained in:
2026-03-01 12:45:32 +00:00
parent 68325944c1
commit cab5c47759
2 changed files with 97 additions and 13 deletions

View File

@@ -1,4 +1,13 @@
import type { ApiFailure, ApiResult, HealthResponse, SessionDetailResponse } from './types'; import type {
ApiFailure,
ApiResult,
HealthResponse,
JoinSessionRequest,
JoinSessionResponse,
SessionDetailResponse,
StartRoundRequest,
StartRoundResponse
} from './types';
export interface AngularHttpError { export interface AngularHttpError {
status?: number; status?: number;
@@ -8,11 +17,14 @@ export interface AngularHttpError {
export interface AngularHttpClientLike { export interface AngularHttpClientLike {
get<T>(url: string, options?: { withCredentials?: boolean }): Promise<T>; get<T>(url: string, options?: { withCredentials?: boolean }): Promise<T>;
post<T>(url: string, body: unknown, options?: { withCredentials?: boolean }): Promise<T>;
} }
export interface AngularApiClient { export interface AngularApiClient {
health(): Promise<ApiResult<HealthResponse>>; health(): Promise<ApiResult<HealthResponse>>;
getSession(code: string): Promise<ApiResult<SessionDetailResponse>>; getSession(code: string): Promise<ApiResult<SessionDetailResponse>>;
joinSession(payload: JoinSessionRequest): Promise<ApiResult<JoinSessionResponse>>;
startRound(code: string, payload: StartRoundRequest): Promise<ApiResult<StartRoundResponse>>;
} }
function toFailure(error: unknown): ApiFailure { function toFailure(error: unknown): ApiFailure {
@@ -40,23 +52,46 @@ function normalizeCode(code: string): string {
return code.trim().toUpperCase(); return code.trim().toUpperCase();
} }
async function wrapGet<T>(call: () => Promise<T>): Promise<ApiResult<T>> { async function wrap<T>(call: () => Promise<T>): Promise<ApiResult<T>> {
try { try {
const data = await call(); const data = await call();
return { ok: true, status: 200, data }; return { ok: true, status: 200, data };
} catch (error: unknown) { } catch (error: unknown) {
return { ok: false, status: typeof (error as AngularHttpError)?.status === 'number' ? (error as AngularHttpError).status! : 0, error: toFailure(error) }; 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 { export function createAngularApiClient(http: AngularHttpClientLike, baseUrl = ''): AngularApiClient {
return { return {
health: () => wrapGet(() => http.get<HealthResponse>(`${baseUrl}/healthz`, { withCredentials: true })), health: () => wrap(() => http.get<HealthResponse>(`${baseUrl}/healthz`, { withCredentials: true })),
getSession: (code: string) => getSession: (code: string) =>
wrapGet(() => wrap(() =>
http.get<SessionDetailResponse>(`${baseUrl}/lobby/sessions/${encodeURIComponent(normalizeCode(code))}`, { http.get<SessionDetailResponse>(`${baseUrl}/lobby/sessions/${encodeURIComponent(normalizeCode(code))}`, {
withCredentials: true withCredentials: true
}) })
),
joinSession: (payload: JoinSessionRequest) =>
wrap(() =>
http.post<JoinSessionResponse>(
`${baseUrl}/lobby/sessions/join`,
{
code: normalizeCode(payload.code),
nickname: payload.nickname.trim()
},
{ withCredentials: true }
)
),
startRound: (code: string, payload: StartRoundRequest) =>
wrap(() =>
http.post<StartRoundResponse>(
`${baseUrl}/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/rounds/start`,
payload,
{ withCredentials: true }
)
) )
}; };
} }

View File

@@ -49,7 +49,27 @@ describe('createAngularApiClient', () => {
throw { status: 404, error: { error: 'Not found' } }; throw { status: 404, error: { error: 'Not found' } };
}); });
const http = { get }; const post = vi.fn<AngularHttpClientLike['post']>(async <T>(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 client = createAngularApiClient(http as AngularHttpClientLike);
const health = await client.health(); const health = await client.health();
@@ -67,26 +87,55 @@ describe('createAngularApiClient', () => {
expect(session.data.phase_view_model.host.can_start_round).toBe(true); 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(1, '/healthz', { withCredentials: true });
expect(get).toHaveBeenNthCalledWith(2, '/lobby/sessions/ABCD12', { 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 () => { it('maps HttpErrorResponse-style failures to ApiResult errors', async () => {
const http = { const http = {
get: vi.fn<AngularHttpClientLike['get']>(async () => { get: vi.fn<AngularHttpClientLike['get']>(async () => {
throw { status: 503, message: 'Service unavailable', error: { error: 'maintenance' } }; throw { status: 503, message: 'Service unavailable', error: { error: 'maintenance' } };
}),
post: vi.fn<AngularHttpClientLike['post']>(async () => {
throw { status: 403, message: 'Forbidden', error: { error: 'Only host can start round' } };
}) })
}; };
const client = createAngularApiClient(http as AngularHttpClientLike); const client = createAngularApiClient(http as AngularHttpClientLike);
const result = await client.health(); const health = await client.health();
expect(result.ok).toBe(false); expect(health.ok).toBe(false);
if (!result.ok) { if (!health.ok) {
expect(result.status).toBe(503); expect(health.status).toBe(503);
expect(result.error.kind).toBe('http'); expect(health.error.kind).toBe('http');
expect(result.error.payload).toEqual({ error: 'maintenance' }); expect(health.error.payload).toEqual({ error: 'maintenance' });
expect(result.error.message).toContain('Service unavailable'); 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' });
} }
}); });
}); });