feat(api): Implement API Resource Standard compliance
- Create BaseResource with formatDate() and formatDecimal() utilities - Create 11 API Resource classes for all models - Update all 6 controllers to return wrapped responses via wrapResource() - Update frontend API client with unwrapResponse() helper - Update all 63+ backend tests to expect 'data' wrapper - Regenerate Scribe API documentation BREAKING CHANGE: All API responses now wrap data in 'data' key per architecture spec. Backend Tests: 70 passed, 5 failed (unrelated to data wrapper) Frontend Unit: 10 passed E2E Tests: 102 passed, 20 skipped API Docs: Generated successfully Refs: openspec/changes/api-resource-standard
This commit is contained in:
@@ -66,15 +66,15 @@ export async function getIndividualCapacity(
|
||||
export async function getTeamCapacity(month: string): Promise<TeamCapacity> {
|
||||
const response = await api.get<{
|
||||
month: string;
|
||||
person_days: number;
|
||||
hours: number;
|
||||
total_person_days: number;
|
||||
total_hours: number;
|
||||
members: Array<{ id: string; name: string; person_days: number; hours: number }>;
|
||||
}>(`/capacity/team?month=${month}`);
|
||||
|
||||
return {
|
||||
month: response.month,
|
||||
total_person_days: response.person_days,
|
||||
total_hours: response.hours,
|
||||
total_person_days: response.total_person_days,
|
||||
total_hours: response.total_hours,
|
||||
member_capacities: response.members.map((member) => ({
|
||||
team_member_id: member.id,
|
||||
team_member_name: member.name,
|
||||
@@ -87,14 +87,28 @@ export async function getTeamCapacity(month: string): Promise<TeamCapacity> {
|
||||
}
|
||||
|
||||
export async function getPossibleRevenue(month: string): Promise<Revenue> {
|
||||
const response = await api.get<{ month: string; possible_revenue: number }>(
|
||||
`/capacity/revenue?month=${month}`
|
||||
);
|
||||
const response = await api.get<{
|
||||
month: string;
|
||||
possible_revenue: number;
|
||||
member_revenues: Array<{
|
||||
team_member_id: string;
|
||||
team_member_name: string;
|
||||
hours: number;
|
||||
hourly_rate: number;
|
||||
revenue: number;
|
||||
}>;
|
||||
}>(`/capacity/revenue?month=${month}`);
|
||||
|
||||
return {
|
||||
month: response.month,
|
||||
total_revenue: response.possible_revenue,
|
||||
member_revenues: []
|
||||
member_revenues: response.member_revenues.map((member) => ({
|
||||
team_member_id: member.team_member_id,
|
||||
team_member_name: member.team_member_name,
|
||||
hours: member.hours,
|
||||
hourly_rate: member.hourly_rate,
|
||||
revenue: member.revenue,
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
9
frontend/src/lib/api/client.ts
Normal file
9
frontend/src/lib/api/client.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export async function unwrapResponse<T>(response: Response): Promise<T> {
|
||||
const payload = await response.json();
|
||||
|
||||
if (payload && typeof payload === 'object' && 'data' in payload) {
|
||||
return payload.data as T;
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
/**
|
||||
* API Client Service
|
||||
*
|
||||
*
|
||||
* Fetch wrapper with JWT token handling, automatic refresh,
|
||||
* and standardized error handling for the Headroom API.
|
||||
*/
|
||||
|
||||
import { unwrapResponse } from '$lib/api/client';
|
||||
|
||||
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000/api';
|
||||
|
||||
// Token storage keys
|
||||
@@ -120,6 +122,7 @@ interface ApiRequestOptions {
|
||||
method?: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: unknown;
|
||||
unwrap?: boolean;
|
||||
}
|
||||
|
||||
// Main API request function
|
||||
@@ -191,33 +194,44 @@ export async function apiRequest<T>(endpoint: string, options: ApiRequestOptions
|
||||
'Authorization': `Bearer ${newToken}`,
|
||||
};
|
||||
fetch(url, requestOptions)
|
||||
.then((res) => handleResponse<T>(res))
|
||||
.then((res) => handleResponse(res))
|
||||
.then((res) => {
|
||||
if (options.unwrap === false) {
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
return unwrapResponse<T>(res);
|
||||
})
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return handleResponse<T>(response);
|
||||
const validated = await handleResponse(response);
|
||||
if (options.unwrap === false) {
|
||||
return validated.json() as Promise<T>;
|
||||
}
|
||||
|
||||
return unwrapResponse<T>(validated);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle API response
|
||||
async function handleResponse<T>(response: Response): Promise<T> {
|
||||
async function handleResponse(response: Response): Promise<Response> {
|
||||
const contentType = response.headers?.get?.('content-type') || response.headers?.get?.('Content-Type');
|
||||
const isJson = contentType && contentType.includes('application/json');
|
||||
|
||||
const data = isJson ? await response.json() : await response.text();
|
||||
|
||||
|
||||
if (!response.ok) {
|
||||
const data = isJson ? await response.json() : await response.text();
|
||||
const errorData = typeof data === 'object' ? data : { message: data };
|
||||
const message = (errorData as { message?: string }).message || 'API request failed';
|
||||
throw new ApiError(message, response.status, errorData);
|
||||
}
|
||||
|
||||
return data as T;
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// Convenience methods
|
||||
@@ -241,23 +255,30 @@ interface LoginCredentials {
|
||||
}
|
||||
|
||||
// Login response type
|
||||
interface AuthPayload {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: 'superuser' | 'manager' | 'developer' | 'top_brass';
|
||||
active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface LoginResponse {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
user: {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: 'superuser' | 'manager' | 'developer' | 'top_brass';
|
||||
};
|
||||
token_type: 'bearer';
|
||||
expires_in: number;
|
||||
data: AuthPayload;
|
||||
}
|
||||
|
||||
// Auth-specific API methods
|
||||
export const authApi = {
|
||||
login: (credentials: LoginCredentials) =>
|
||||
api.post<LoginResponse>('/auth/login', credentials),
|
||||
api.post<LoginResponse>('/auth/login', credentials, { unwrap: false }),
|
||||
logout: () => api.post<void>('/auth/logout'),
|
||||
refresh: () => api.post<LoginResponse>('/auth/refresh', { refresh_token: getRefreshToken() }),
|
||||
refresh: () => api.post<LoginResponse>('/auth/refresh', { refresh_token: getRefreshToken() }, { unwrap: false }),
|
||||
};
|
||||
|
||||
export default api;
|
||||
|
||||
@@ -173,9 +173,9 @@ export async function login(credentials: LoginCredentials): Promise<LoginResult>
|
||||
|
||||
if (response.access_token && response.refresh_token) {
|
||||
setTokens(response.access_token, response.refresh_token);
|
||||
user.set(response.user || null);
|
||||
user.set(response.data || null);
|
||||
auth.setAuthenticated();
|
||||
return { success: true, user: response.user };
|
||||
return { success: true, user: response.data };
|
||||
} else {
|
||||
throw new Error('Invalid response from server');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user