Adds front-end set-up
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
import type { ProblemDetails } from '@/api/types';
|
||||
import { getAppConfig } from '@/lib/config';
|
||||
|
||||
/**
|
||||
* Typed error thrown for any non-2xx API response. Wraps an RFC 9457
|
||||
* ProblemDetails body so callers can present context-aware messages
|
||||
* (BR-U1-08, NFR-U1-05 / Q5-B) instead of raw stack traces.
|
||||
*/
|
||||
export class ProblemDetailsError extends Error {
|
||||
readonly status: number;
|
||||
readonly problem: ProblemDetails;
|
||||
|
||||
constructor(status: number, problem: ProblemDetails) {
|
||||
super(problem.title ?? problem.detail ?? `Request failed with status ${status}`);
|
||||
this.name = 'ProblemDetailsError';
|
||||
this.status = status;
|
||||
this.problem = problem;
|
||||
}
|
||||
}
|
||||
|
||||
/** Thrown when the network request itself fails (offline, timeout, DNS). */
|
||||
export class NetworkError extends Error {
|
||||
constructor(message = 'Network request failed') {
|
||||
super(message);
|
||||
this.name = 'NetworkError';
|
||||
}
|
||||
}
|
||||
|
||||
export interface RequestOptions extends Omit<RequestInit, 'body'> {
|
||||
/** Parsed and JSON-serialized automatically when present. */
|
||||
body?: unknown;
|
||||
/** Skip the 401 refresh+retry interceptor (used by the refresh call itself). */
|
||||
skipAuthRefresh?: boolean;
|
||||
}
|
||||
|
||||
type RefreshHandler = () => Promise<string | null>;
|
||||
type AuthFailureHandler = () => void;
|
||||
|
||||
/**
|
||||
* Thin fetch wrapper. All calls send credentials so the httpOnly refresh
|
||||
* cookie travels with the request (BR-U1-03). The access token is held only
|
||||
* in memory and injected per request (BR-U1-02).
|
||||
*/
|
||||
export class ApiClient {
|
||||
private readonly baseUrl: string;
|
||||
private accessToken: string | null = null;
|
||||
private refreshHandler: RefreshHandler | null = null;
|
||||
private authFailureHandler: AuthFailureHandler | null = null;
|
||||
|
||||
constructor(baseUrl: string) {
|
||||
this.baseUrl = baseUrl.replace(/\/$/, '');
|
||||
}
|
||||
|
||||
setAccessToken(token: string | null): void {
|
||||
this.accessToken = token;
|
||||
}
|
||||
|
||||
/** Registered by AuthContext: performs a cookie-based refresh, returns the new token or null. */
|
||||
setRefreshHandler(handler: RefreshHandler | null): void {
|
||||
this.refreshHandler = handler;
|
||||
}
|
||||
|
||||
/** Registered by AuthContext: invoked when refresh fails and auth must be cleared. */
|
||||
setAuthFailureHandler(handler: AuthFailureHandler | null): void {
|
||||
this.authFailureHandler = handler;
|
||||
}
|
||||
|
||||
get<T>(path: string, options?: RequestOptions): Promise<T> {
|
||||
return this.request<T>(path, { ...options, method: 'GET' });
|
||||
}
|
||||
|
||||
post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {
|
||||
return this.request<T>(path, { ...options, method: 'POST', body });
|
||||
}
|
||||
|
||||
put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {
|
||||
return this.request<T>(path, { ...options, method: 'PUT', body });
|
||||
}
|
||||
|
||||
delete<T>(path: string, options?: RequestOptions): Promise<T> {
|
||||
return this.request<T>(path, { ...options, method: 'DELETE' });
|
||||
}
|
||||
|
||||
private async request<T>(path: string, options: RequestOptions): Promise<T> {
|
||||
let response = await this.rawFetch(path, options);
|
||||
|
||||
// 401 intercept: try a single cookie-based refresh, then retry once (BR-U1-04).
|
||||
if (response.status === 401 && !options.skipAuthRefresh && this.refreshHandler !== null) {
|
||||
const newToken = await this.refreshHandler();
|
||||
if (newToken !== null) {
|
||||
response = await this.rawFetch(path, options);
|
||||
} else {
|
||||
this.authFailureHandler?.();
|
||||
}
|
||||
}
|
||||
|
||||
return this.parse<T>(response);
|
||||
}
|
||||
|
||||
private async rawFetch(path: string, options: RequestOptions): Promise<Response> {
|
||||
const { body, skipAuthRefresh: _skip, headers, ...rest } = options;
|
||||
const finalHeaders = new Headers(headers);
|
||||
|
||||
if (body !== undefined && body !== null) {
|
||||
finalHeaders.set('Content-Type', 'application/json');
|
||||
}
|
||||
if (this.accessToken !== null) {
|
||||
finalHeaders.set('Authorization', `Bearer ${this.accessToken}`);
|
||||
}
|
||||
|
||||
try {
|
||||
return await fetch(`${this.baseUrl}${path}`, {
|
||||
...rest,
|
||||
headers: finalHeaders,
|
||||
credentials: 'include',
|
||||
body: body !== undefined && body !== null ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
} catch (cause) {
|
||||
throw new NetworkError(cause instanceof Error ? cause.message : undefined);
|
||||
}
|
||||
}
|
||||
|
||||
private async parse<T>(response: Response): Promise<T> {
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
const data = text.length > 0 ? safeJsonParse(text) : undefined;
|
||||
|
||||
if (!response.ok) {
|
||||
const problem: ProblemDetails = isProblemDetails(data)
|
||||
? data
|
||||
: { status: response.status, title: response.statusText };
|
||||
throw new ProblemDetailsError(response.status, problem);
|
||||
}
|
||||
|
||||
return data as T;
|
||||
}
|
||||
}
|
||||
|
||||
function safeJsonParse(text: string): unknown {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
function isProblemDetails(value: unknown): value is ProblemDetails {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
|
||||
/** Shared singleton API client configured from the typed environment. */
|
||||
export const api = new ApiClient(getAppConfig().apiBaseUrl);
|
||||
@@ -0,0 +1,35 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* Application configuration sourced from Vite env (Q6-A).
|
||||
* Strong typing comes from vite-env.d.ts; the optional Zod parse below runs
|
||||
* once and only warns in development — production trusts the build-time env.
|
||||
*/
|
||||
const configSchema = z.object({
|
||||
apiBaseUrl: z.string().url(),
|
||||
});
|
||||
|
||||
export type AppConfig = z.infer<typeof configSchema>;
|
||||
|
||||
let cached: AppConfig | null = null;
|
||||
|
||||
export function getAppConfig(): AppConfig {
|
||||
if (cached !== null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const raw: AppConfig = {
|
||||
apiBaseUrl: import.meta.env.VITE_API_BASE_URL,
|
||||
};
|
||||
|
||||
if (import.meta.env.DEV) {
|
||||
const result = configSchema.safeParse(raw);
|
||||
if (!result.success) {
|
||||
// Development-only warning; never throws so the app still boots.
|
||||
console.warn('[config] Invalid environment configuration:', result.error.format());
|
||||
}
|
||||
}
|
||||
|
||||
cached = raw;
|
||||
return cached;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { clsx, type ClassValue } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
/**
|
||||
* Merge conditional class names and resolve Tailwind conflicts.
|
||||
* Standard shadcn/ui helper.
|
||||
*/
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
Reference in New Issue
Block a user