Refactor API layer into structured domain-specific modules

- Created new api/ directory with domain-specific API modules:
  - api/client.ts: Base API client with error handling
  - api/auth.ts: Authentication endpoints
  - api/exchange.ts: Exchange/price endpoints
  - api/trades.ts: User trade endpoints
  - api/profile.ts: Profile management endpoints
  - api/invites.ts: Invite endpoints
  - api/admin.ts: Admin endpoints
  - api/index.ts: Centralized exports

- Migrated all API calls from ad-hoc api.get/post/put to typed domain APIs
- Updated all imports across codebase
- Fixed test mocks to use new API structure
- Fixed type issues in validation utilities
- Removed old api.ts file

Benefits:
- Type-safe endpoints (no more string typos)
- Centralized API surface (easy to discover endpoints)
- Better organization (domain-specific modules)
- Uses generated OpenAPI types automatically
This commit is contained in:
counterweight 2025-12-25 20:32:11 +01:00
parent 6d0f125536
commit a6fa6a8012
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C
24 changed files with 529 additions and 255 deletions

156
frontend/app/api/admin.ts Normal file
View file

@ -0,0 +1,156 @@
import { client } from "./client";
import { components } from "../generated/api";
type AdminUserResponse = components["schemas"]["AdminUserResponse"];
type PaginatedInvites = components["schemas"]["PaginatedResponse_InviteResponse_"];
type AdminExchangeResponse = components["schemas"]["AdminExchangeResponse"];
type AvailabilityResponse = components["schemas"]["AvailabilityResponse"];
type PriceHistoryRecord = components["schemas"]["PriceHistoryResponse"];
interface CreateInviteRequest {
godfather_id: number;
}
interface UpdateAvailabilityRequest {
date: string;
slots: Array<{ start_time: string; end_time: string }>;
}
interface CopyAvailabilityRequest {
source_date: string;
target_dates: string[];
}
interface GetPastTradesParams {
status?: string;
user_search?: string;
}
/**
* Admin API endpoints
*/
export const adminApi = {
/**
* Get all users (for dropdowns, etc.)
*/
getUsers(): Promise<AdminUserResponse[]> {
return client.get<AdminUserResponse[]>("/api/admin/users");
},
/**
* Get paginated invites
*/
getInvites(page: number, perPage: number = 10, status?: string): Promise<PaginatedInvites> {
const params = new URLSearchParams();
params.append("page", page.toString());
params.append("per_page", perPage.toString());
if (status) {
params.append("status", status);
}
return client.get<PaginatedInvites>(`/api/admin/invites?${params.toString()}`);
},
/**
* Create a new invite
*/
createInvite(request: CreateInviteRequest): Promise<void> {
return client.post<void>("/api/admin/invites", request);
},
/**
* Revoke an invite
*/
revokeInvite(inviteId: number): Promise<void> {
return client.post<void>(`/api/admin/invites/${inviteId}/revoke`);
},
/**
* Get upcoming trades
*/
getUpcomingTrades(): Promise<AdminExchangeResponse[]> {
return client.get<AdminExchangeResponse[]>("/api/admin/trades/upcoming");
},
/**
* Get past trades with optional filters
*/
getPastTrades(params?: GetPastTradesParams): Promise<AdminExchangeResponse[]> {
const searchParams = new URLSearchParams();
if (params?.status) {
searchParams.append("status", params.status);
}
if (params?.user_search) {
searchParams.append("user_search", params.user_search);
}
const queryString = searchParams.toString();
const url = queryString ? `/api/admin/trades/past?${queryString}` : "/api/admin/trades/past";
return client.get<AdminExchangeResponse[]>(url);
},
/**
* Complete a trade
*/
completeTrade(publicId: string): Promise<AdminExchangeResponse> {
return client.post<AdminExchangeResponse>(
`/api/admin/trades/${encodeURIComponent(publicId)}/complete`,
{}
);
},
/**
* Mark a trade as no-show
*/
noShowTrade(publicId: string): Promise<AdminExchangeResponse> {
return client.post<AdminExchangeResponse>(
`/api/admin/trades/${encodeURIComponent(publicId)}/no-show`,
{}
);
},
/**
* Cancel a trade (admin)
*/
cancelTrade(publicId: string): Promise<AdminExchangeResponse> {
return client.post<AdminExchangeResponse>(
`/api/admin/trades/${encodeURIComponent(publicId)}/cancel`,
{}
);
},
/**
* Get availability for a date range
*/
getAvailability(fromDate: string, toDate: string): Promise<AvailabilityResponse> {
return client.get<AvailabilityResponse>(
`/api/admin/availability?from=${encodeURIComponent(fromDate)}&to=${encodeURIComponent(toDate)}`
);
},
/**
* Update availability for a specific date
*/
updateAvailability(request: UpdateAvailabilityRequest): Promise<void> {
return client.put<void>("/api/admin/availability", request);
},
/**
* Copy availability from one date to multiple dates
*/
copyAvailability(request: CopyAvailabilityRequest): Promise<void> {
return client.post<void>("/api/admin/availability/copy", request);
},
/**
* Get price history records
*/
getPriceHistory(): Promise<PriceHistoryRecord[]> {
return client.get<PriceHistoryRecord[]>("/api/audit/price-history");
},
/**
* Trigger a price fetch
*/
fetchPrice(): Promise<PriceHistoryRecord> {
return client.post<PriceHistoryRecord>("/api/audit/price-history/fetch", {});
},
};

41
frontend/app/api/auth.ts Normal file
View file

@ -0,0 +1,41 @@
import { client } from "./client";
import { components } from "../generated/api";
type User = components["schemas"]["UserResponse"];
/**
* Authentication API endpoints
*/
export const authApi = {
/**
* Get current authenticated user
*/
getMe(): Promise<User> {
return client.get<User>("/api/auth/me");
},
/**
* Login with email and password
*/
login(email: string, password: string): Promise<User> {
return client.post<User>("/api/auth/login", { email, password });
},
/**
* Register a new user with invite code
*/
register(email: string, password: string, inviteIdentifier: string): Promise<User> {
return client.post<User>("/api/auth/register", {
email,
password,
invite_identifier: inviteIdentifier,
});
},
/**
* Logout current user
*/
logout(): Promise<void> {
return client.post<void>("/api/auth/logout");
},
};

View file

@ -0,0 +1,71 @@
import { API_URL } from "../config";
/**
* Base API client that centralizes fetch configuration.
* All requests include credentials and proper headers.
*/
export class ApiError extends Error {
constructor(
message: string,
public status: number,
public data?: unknown
) {
super(message);
this.name = "ApiError";
}
}
async function request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
const url = `${API_URL}${endpoint}`;
const headers: Record<string, string> = {
...(options.headers as Record<string, string>),
};
if (options.body && typeof options.body === "string") {
headers["Content-Type"] = "application/json";
}
const res = await fetch(url, {
...options,
headers,
credentials: "include",
});
if (!res.ok) {
let data: unknown;
try {
data = await res.json();
} catch {
// Response wasn't JSON
}
throw new ApiError(`Request failed: ${res.status}`, res.status, data);
}
return res.json();
}
/**
* Base API client methods.
* Domain-specific APIs should use these internally.
*/
export const client = {
get<T>(endpoint: string): Promise<T> {
return request<T>(endpoint);
},
post<T>(endpoint: string, body?: unknown): Promise<T> {
return request<T>(endpoint, {
method: "POST",
body: body ? JSON.stringify(body) : undefined,
});
},
put<T>(endpoint: string, body?: unknown): Promise<T> {
return request<T>(endpoint, {
method: "PUT",
body: body ? JSON.stringify(body) : undefined,
});
},
};

View file

@ -0,0 +1,41 @@
import { client } from "./client";
import { components } from "../generated/api";
type ExchangePriceResponse = components["schemas"]["ExchangePriceResponse"];
type AvailableSlotsResponse = components["schemas"]["AvailableSlotsResponse"];
type ExchangeResponse = components["schemas"]["ExchangeResponse"];
interface CreateExchangeRequest {
slot_start: string;
direction: "buy" | "sell";
bitcoin_transfer_method: "onchain" | "lightning";
eur_amount: number;
}
/**
* Exchange API endpoints
*/
export const exchangeApi = {
/**
* Get current exchange price
*/
getPrice(): Promise<ExchangePriceResponse> {
return client.get<ExchangePriceResponse>("/api/exchange/price");
},
/**
* Get available slots for a specific date
*/
getSlots(date: string): Promise<AvailableSlotsResponse> {
return client.get<AvailableSlotsResponse>(
`/api/exchange/slots?date=${encodeURIComponent(date)}`
);
},
/**
* Create a new exchange/trade
*/
createExchange(request: CreateExchangeRequest): Promise<ExchangeResponse> {
return client.post<ExchangeResponse>("/api/exchange", request);
},
};

12
frontend/app/api/index.ts Normal file
View file

@ -0,0 +1,12 @@
/**
* Centralized API exports.
* Import domain-specific APIs from here.
*/
export { ApiError, client } from "./client";
export { authApi } from "./auth";
export { exchangeApi } from "./exchange";
export { tradesApi } from "./trades";
export { profileApi } from "./profile";
export { invitesApi } from "./invites";
export { adminApi } from "./admin";

View file

@ -0,0 +1,24 @@
import { client } from "./client";
import { components } from "../generated/api";
type Invite = components["schemas"]["UserInviteResponse"];
type InviteCheckResponse = components["schemas"]["InviteCheckResponse"];
/**
* Invites API endpoints (user-facing)
*/
export const invitesApi = {
/**
* Get all invites for the current user
*/
getInvites(): Promise<Invite[]> {
return client.get<Invite[]>("/api/invites");
},
/**
* Check if an invite code is valid
*/
checkInvite(code: string): Promise<InviteCheckResponse> {
return client.get<InviteCheckResponse>(`/api/invites/${encodeURIComponent(code)}/check`);
},
};

View file

@ -0,0 +1,30 @@
import { client } from "./client";
import { components } from "../generated/api";
type ProfileData = components["schemas"]["ProfileResponse"];
interface UpdateProfileRequest {
contact_email: string | null;
telegram: string | null;
signal: string | null;
nostr_npub: string | null;
}
/**
* Profile API endpoints
*/
export const profileApi = {
/**
* Get current user's profile
*/
getProfile(): Promise<ProfileData> {
return client.get<ProfileData>("/api/profile");
},
/**
* Update current user's profile
*/
updateProfile(request: UpdateProfileRequest): Promise<ProfileData> {
return client.put<ProfileData>("/api/profile", request);
},
};

View file

@ -0,0 +1,30 @@
import { client } from "./client";
import { components } from "../generated/api";
type ExchangeResponse = components["schemas"]["ExchangeResponse"];
/**
* Trades API endpoints (user-facing)
*/
export const tradesApi = {
/**
* Get all trades for the current user
*/
getTrades(): Promise<ExchangeResponse[]> {
return client.get<ExchangeResponse[]>("/api/trades");
},
/**
* Get a specific trade by public ID
*/
getTrade(publicId: string): Promise<ExchangeResponse> {
return client.get<ExchangeResponse>(`/api/trades/${encodeURIComponent(publicId)}`);
},
/**
* Cancel a trade
*/
cancelTrade(publicId: string): Promise<ExchangeResponse> {
return client.post<ExchangeResponse>(`/api/trades/${encodeURIComponent(publicId)}/cancel`, {});
},
};