[READY][SPA][P2] Angular API-client (health + session read) (#168) #170
62
frontend/src/api/angular-client.ts
Normal file
62
frontend/src/api/angular-client.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import type { ApiFailure, ApiResult, HealthResponse, SessionDetailResponse } from './types';
|
||||
|
||||
export interface AngularHttpError {
|
||||
status?: number;
|
||||
message?: string;
|
||||
error?: unknown;
|
||||
}
|
||||
|
||||
export interface AngularHttpClientLike {
|
||||
get<T>(url: string, options?: { withCredentials?: boolean }): Promise<T>;
|
||||
}
|
||||
|
||||
export interface AngularApiClient {
|
||||
health(): Promise<ApiResult<HealthResponse>>;
|
||||
getSession(code: string): Promise<ApiResult<SessionDetailResponse>>;
|
||||
}
|
||||
|
||||
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 wrapGet<T>(call: () => Promise<T>): Promise<ApiResult<T>> {
|
||||
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: () => wrapGet(() => http.get<HealthResponse>(`${baseUrl}/healthz`, { withCredentials: true })),
|
||||
getSession: (code: string) =>
|
||||
wrapGet(() =>
|
||||
http.get<SessionDetailResponse>(`${baseUrl}/lobby/sessions/${encodeURIComponent(normalizeCode(code))}`, {
|
||||
withCredentials: true
|
||||
})
|
||||
)
|
||||
};
|
||||
}
|
||||
92
frontend/tests/angular-api-client.test.ts
Normal file
92
frontend/tests/angular-api-client.test.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
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<AngularHttpClientLike['get']>(async <T>(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 http = { get };
|
||||
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);
|
||||
}
|
||||
|
||||
expect(get).toHaveBeenNthCalledWith(1, '/healthz', { withCredentials: true });
|
||||
expect(get).toHaveBeenNthCalledWith(2, '/lobby/sessions/ABCD12', { withCredentials: true });
|
||||
});
|
||||
|
||||
it('maps HttpErrorResponse-style failures to ApiResult errors', async () => {
|
||||
const http = {
|
||||
get: vi.fn<AngularHttpClientLike['get']>(async () => {
|
||||
throw { status: 503, message: 'Service unavailable', error: { error: 'maintenance' } };
|
||||
})
|
||||
};
|
||||
|
||||
const client = createAngularApiClient(http as AngularHttpClientLike);
|
||||
const result = await client.health();
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.status).toBe(503);
|
||||
expect(result.error.kind).toBe('http');
|
||||
expect(result.error.payload).toEqual({ error: 'maintenance' });
|
||||
expect(result.error.message).toContain('Service unavailable');
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user