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:
parent
6d0f125536
commit
a6fa6a8012
24 changed files with 529 additions and 255 deletions
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { Permission } from "../../auth-context";
|
||||
import { api } from "../../api";
|
||||
import { adminApi } from "../../api";
|
||||
import { Header } from "../../components/Header";
|
||||
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
||||
import { components } from "../../generated/api";
|
||||
|
|
@ -25,7 +25,6 @@ import {
|
|||
const { slotDurationMinutes, maxAdvanceDays, minAdvanceDays } = constants.exchange;
|
||||
|
||||
type _AvailabilityDay = components["schemas"]["AvailabilityDay"];
|
||||
type AvailabilityResponse = components["schemas"]["AvailabilityResponse"];
|
||||
type TimeSlot = components["schemas"]["TimeSlot"];
|
||||
|
||||
// Generate time options for dropdowns (15-min intervals)
|
||||
|
|
@ -73,9 +72,7 @@ export default function AdminAvailabilityPage() {
|
|||
try {
|
||||
const fromDate = formatDate(dateRange[0]);
|
||||
const toDate = formatDate(dateRange[dateRange.length - 1]);
|
||||
const data = await api.get<AvailabilityResponse>(
|
||||
`/api/admin/availability?from=${fromDate}&to=${toDate}`
|
||||
);
|
||||
const data = await adminApi.getAvailability(fromDate, toDate);
|
||||
|
||||
const map = new Map<string, TimeSlot[]>();
|
||||
for (const day of data.days) {
|
||||
|
|
@ -140,7 +137,7 @@ export default function AdminAvailabilityPage() {
|
|||
end_time: s.end_time + ":00",
|
||||
}));
|
||||
|
||||
await api.put("/api/admin/availability", {
|
||||
await adminApi.updateAvailability({
|
||||
date: formatDate(selectedDate),
|
||||
slots,
|
||||
});
|
||||
|
|
@ -161,7 +158,7 @@ export default function AdminAvailabilityPage() {
|
|||
setError(null);
|
||||
|
||||
try {
|
||||
await api.put("/api/admin/availability", {
|
||||
await adminApi.updateAvailability({
|
||||
date: formatDate(selectedDate),
|
||||
slots: [],
|
||||
});
|
||||
|
|
@ -203,7 +200,7 @@ export default function AdminAvailabilityPage() {
|
|||
setError(null);
|
||||
|
||||
try {
|
||||
await api.post("/api/admin/availability/copy", {
|
||||
await adminApi.copyAvailability({
|
||||
source_date: copySource,
|
||||
target_dates: Array.from(copyTargets),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { Permission } from "../../auth-context";
|
||||
import { api } from "../../api";
|
||||
import { adminApi } from "../../api";
|
||||
import { Header } from "../../components/Header";
|
||||
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
||||
import { components } from "../../generated/api";
|
||||
|
|
@ -41,7 +41,7 @@ export default function AdminInvitesPage() {
|
|||
|
||||
const fetchUsers = useCallback(async () => {
|
||||
try {
|
||||
const data = await api.get<UserOption[]>("/api/admin/users");
|
||||
const data = await adminApi.getUsers();
|
||||
setUsers(data);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch users:", err);
|
||||
|
|
@ -51,11 +51,7 @@ export default function AdminInvitesPage() {
|
|||
const fetchInvites = useCallback(async (page: number, status: string) => {
|
||||
setError(null);
|
||||
try {
|
||||
let url = `/api/admin/invites?page=${page}&per_page=10`;
|
||||
if (status) {
|
||||
url += `&status=${status}`;
|
||||
}
|
||||
const data = await api.get<PaginatedInvites>(url);
|
||||
const data = await adminApi.getInvites(page, 10, status || undefined);
|
||||
setData(data);
|
||||
} catch (err) {
|
||||
setData(null);
|
||||
|
|
@ -80,7 +76,7 @@ export default function AdminInvitesPage() {
|
|||
setCreateError(null);
|
||||
|
||||
try {
|
||||
await api.post("/api/admin/invites", {
|
||||
await adminApi.createInvite({
|
||||
godfather_id: parseInt(newGodfatherId),
|
||||
});
|
||||
setNewGodfatherId("");
|
||||
|
|
@ -95,7 +91,7 @@ export default function AdminInvitesPage() {
|
|||
|
||||
const handleRevoke = async (inviteId: number) => {
|
||||
try {
|
||||
await api.post(`/api/admin/invites/${inviteId}/revoke`);
|
||||
await adminApi.revokeInvite(inviteId);
|
||||
setError(null);
|
||||
fetchInvites(page, statusFilter);
|
||||
} catch (err) {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { Permission } from "../../auth-context";
|
||||
import { api } from "../../api";
|
||||
import { adminApi } from "../../api";
|
||||
import { sharedStyles } from "../../styles/shared";
|
||||
import { Header } from "../../components/Header";
|
||||
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
||||
|
|
@ -24,7 +24,7 @@ export default function AdminPriceHistoryPage() {
|
|||
setError(null);
|
||||
setIsLoadingData(true);
|
||||
try {
|
||||
const data = await api.get<PriceHistoryRecord[]>("/api/audit/price-history");
|
||||
const data = await adminApi.getPriceHistory();
|
||||
setRecords(data);
|
||||
} catch (err) {
|
||||
setRecords([]);
|
||||
|
|
@ -38,7 +38,7 @@ export default function AdminPriceHistoryPage() {
|
|||
setIsFetching(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.post<PriceHistoryRecord>("/api/audit/price-history/fetch", {});
|
||||
await adminApi.fetchPrice();
|
||||
await fetchRecords();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to fetch price");
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import { useEffect, useState, useCallback, CSSProperties } from "react";
|
||||
import { Permission } from "../../auth-context";
|
||||
import { api } from "../../api";
|
||||
import { adminApi } from "../../api";
|
||||
import { Header } from "../../components/Header";
|
||||
import { SatsDisplay } from "../../components/SatsDisplay";
|
||||
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
||||
|
|
@ -47,7 +47,7 @@ export default function AdminTradesPage() {
|
|||
|
||||
const fetchUpcomingTrades = useCallback(async (): Promise<string | null> => {
|
||||
try {
|
||||
const data = await api.get<AdminExchangeResponse[]>("/api/admin/trades/upcoming");
|
||||
const data = await adminApi.getUpcomingTrades();
|
||||
setUpcomingTrades(data);
|
||||
return null;
|
||||
} catch (err) {
|
||||
|
|
@ -58,21 +58,17 @@ export default function AdminTradesPage() {
|
|||
|
||||
const fetchPastTrades = useCallback(async (): Promise<string | null> => {
|
||||
try {
|
||||
let url = "/api/admin/trades/past";
|
||||
const params = new URLSearchParams();
|
||||
|
||||
const params: { status?: string; user_search?: string } = {};
|
||||
if (statusFilter !== "all") {
|
||||
params.append("status", statusFilter);
|
||||
params.status = statusFilter;
|
||||
}
|
||||
if (userSearch.trim()) {
|
||||
params.append("user_search", userSearch.trim());
|
||||
params.user_search = userSearch.trim();
|
||||
}
|
||||
|
||||
if (params.toString()) {
|
||||
url += `?${params.toString()}`;
|
||||
}
|
||||
|
||||
const data = await api.get<AdminExchangeResponse[]>(url);
|
||||
const data = await adminApi.getPastTrades(
|
||||
Object.keys(params).length > 0 ? params : undefined
|
||||
);
|
||||
setPastTrades(data);
|
||||
return null;
|
||||
} catch (err) {
|
||||
|
|
@ -105,12 +101,13 @@ export default function AdminTradesPage() {
|
|||
setError(null);
|
||||
|
||||
try {
|
||||
const endpoint =
|
||||
action === "no_show"
|
||||
? `/api/admin/trades/${publicId}/no-show`
|
||||
: `/api/admin/trades/${publicId}/${action}`;
|
||||
|
||||
await api.post<AdminExchangeResponse>(endpoint, {});
|
||||
if (action === "complete") {
|
||||
await adminApi.completeTrade(publicId);
|
||||
} else if (action === "no_show") {
|
||||
await adminApi.noShowTrade(publicId);
|
||||
} else if (action === "cancel") {
|
||||
await adminApi.cancelTrade(publicId);
|
||||
}
|
||||
// Refetch trades - errors from fetch are informational, not critical
|
||||
const [upcomingErr, pastErr] = await Promise.all([fetchUpcomingTrades(), fetchPastTrades()]);
|
||||
const fetchErrors = [upcomingErr, pastErr].filter(Boolean);
|
||||
|
|
|
|||
156
frontend/app/api/admin.ts
Normal file
156
frontend/app/api/admin.ts
Normal 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
41
frontend/app/api/auth.ts
Normal 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");
|
||||
},
|
||||
};
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { API_URL } from "./config";
|
||||
import { API_URL } from "../config";
|
||||
|
||||
/**
|
||||
* Simple API client that centralizes fetch configuration.
|
||||
* Base API client that centralizes fetch configuration.
|
||||
* All requests include credentials and proper headers.
|
||||
*/
|
||||
|
||||
|
|
@ -46,7 +46,11 @@ async function request<T>(endpoint: string, options: RequestInit = {}): Promise<
|
|||
return res.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
/**
|
||||
* Base API client methods.
|
||||
* Domain-specific APIs should use these internally.
|
||||
*/
|
||||
export const client = {
|
||||
get<T>(endpoint: string): Promise<T> {
|
||||
return request<T>(endpoint);
|
||||
},
|
||||
41
frontend/app/api/exchange.ts
Normal file
41
frontend/app/api/exchange.ts
Normal 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
12
frontend/app/api/index.ts
Normal 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";
|
||||
24
frontend/app/api/invites.ts
Normal file
24
frontend/app/api/invites.ts
Normal 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`);
|
||||
},
|
||||
};
|
||||
30
frontend/app/api/profile.ts
Normal file
30
frontend/app/api/profile.ts
Normal 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);
|
||||
},
|
||||
};
|
||||
30
frontend/app/api/trades.ts
Normal file
30
frontend/app/api/trades.ts
Normal 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`, {});
|
||||
},
|
||||
};
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from "react";
|
||||
|
||||
import { api } from "./api";
|
||||
import { authApi } from "./api";
|
||||
import { components } from "./generated/api";
|
||||
import { extractApiErrorMessage } from "./utils/error-handling";
|
||||
|
||||
|
|
@ -54,7 +54,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const userData = await api.get<User>("/api/auth/me");
|
||||
const userData = await authApi.getMe();
|
||||
setUser(userData);
|
||||
} catch {
|
||||
// Not authenticated
|
||||
|
|
@ -65,7 +65,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||
|
||||
const login = async (email: string, password: string) => {
|
||||
try {
|
||||
const userData = await api.post<User>("/api/auth/login", { email, password });
|
||||
const userData = await authApi.login(email, password);
|
||||
setUser(userData);
|
||||
} catch (err) {
|
||||
throw new Error(extractApiErrorMessage(err, "Login failed"));
|
||||
|
|
@ -74,11 +74,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||
|
||||
const register = async (email: string, password: string, inviteIdentifier: string) => {
|
||||
try {
|
||||
const userData = await api.post<User>("/api/auth/register", {
|
||||
email,
|
||||
password,
|
||||
invite_identifier: inviteIdentifier,
|
||||
});
|
||||
const userData = await authApi.register(email, password, inviteIdentifier);
|
||||
setUser(userData);
|
||||
} catch (err) {
|
||||
throw new Error(extractApiErrorMessage(err, "Registration failed"));
|
||||
|
|
@ -87,7 +83,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await api.post("/api/auth/logout");
|
||||
await authApi.logout();
|
||||
} catch {
|
||||
// Ignore errors on logout
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import { useState, useEffect, useCallback } from "react";
|
||||
import { api } from "../../api";
|
||||
import { exchangeApi } from "../../api";
|
||||
import { components } from "../../generated/api";
|
||||
import { formatDate } from "../../utils/date";
|
||||
|
||||
type BookableSlot = components["schemas"]["BookableSlot"];
|
||||
type AvailableSlotsResponse = components["schemas"]["AvailableSlotsResponse"];
|
||||
|
||||
interface UseAvailableSlotsOptions {
|
||||
/** Whether the user is authenticated and authorized */
|
||||
|
|
@ -48,7 +47,7 @@ export function useAvailableSlots(options: UseAvailableSlotsOptions): UseAvailab
|
|||
|
||||
try {
|
||||
const dateStr = formatDate(date);
|
||||
const data = await api.get<AvailableSlotsResponse>(`/api/exchange/slots?date=${dateStr}`);
|
||||
const data = await exchangeApi.getSlots(dateStr);
|
||||
setAvailableSlots(data.slots);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch slots:", err);
|
||||
|
|
@ -70,7 +69,7 @@ export function useAvailableSlots(options: UseAvailableSlotsOptions): UseAvailab
|
|||
const promises = dates.map(async (date) => {
|
||||
try {
|
||||
const dateStr = formatDate(date);
|
||||
const data = await api.get<AvailableSlotsResponse>(`/api/exchange/slots?date=${dateStr}`);
|
||||
const data = await exchangeApi.getSlots(dateStr);
|
||||
if (data.slots.length > 0) {
|
||||
availabilitySet.add(dateStr);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useState, useEffect, useCallback } from "react";
|
||||
import { api } from "../../api";
|
||||
import { exchangeApi } from "../../api";
|
||||
import { components } from "../../generated/api";
|
||||
|
||||
type ExchangePriceResponse = components["schemas"]["ExchangePriceResponse"];
|
||||
|
|
@ -37,7 +37,7 @@ export function useExchangePrice(options: UseExchangePriceOptions = {}): UseExch
|
|||
setError(null);
|
||||
|
||||
try {
|
||||
const data = await api.get<ExchangePriceResponse>("/api/exchange/price");
|
||||
const data = await exchangeApi.getPrice();
|
||||
setPriceData(data);
|
||||
setLastUpdate(new Date());
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
import { useEffect, useState, useCallback, useMemo } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Permission } from "../auth-context";
|
||||
import { api } from "../api";
|
||||
import { exchangeApi, tradesApi } from "../api";
|
||||
import { extractApiErrorMessage } from "../utils/error-handling";
|
||||
import { Header } from "../components/Header";
|
||||
import { LoadingState } from "../components/LoadingState";
|
||||
|
|
@ -166,7 +166,7 @@ export default function ExchangePage() {
|
|||
|
||||
const fetchUserTrades = async () => {
|
||||
try {
|
||||
const data = await api.get<ExchangeResponse[]>("/api/trades");
|
||||
const data = await tradesApi.getTrades();
|
||||
setUserTrades(data);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch user trades:", err);
|
||||
|
|
@ -242,7 +242,7 @@ export default function ExchangePage() {
|
|||
setExistingTradeId(null);
|
||||
|
||||
try {
|
||||
await api.post<ExchangeResponse>("/api/exchange", {
|
||||
await exchangeApi.createExchange({
|
||||
slot_start: selectedSlot.start_time,
|
||||
direction,
|
||||
bitcoin_transfer_method: bitcoinTransferMethod,
|
||||
|
|
|
|||
|
|
@ -9,16 +9,19 @@ import { useEffect, useRef, useState } from "react";
|
|||
* @param delay - Debounce delay in milliseconds (default: 500)
|
||||
* @returns Object containing current errors and a function to manually trigger validation
|
||||
*/
|
||||
export function useDebouncedValidation<T>(
|
||||
export function useDebouncedValidation<
|
||||
T,
|
||||
E extends Record<string, string | undefined> = Record<string, string>,
|
||||
>(
|
||||
formData: T,
|
||||
validator: (data: T) => Record<string, string>,
|
||||
validator: (data: T) => E,
|
||||
delay: number = 500
|
||||
): {
|
||||
errors: Record<string, string>;
|
||||
setErrors: React.Dispatch<React.SetStateAction<Record<string, string>>>;
|
||||
errors: E;
|
||||
setErrors: React.Dispatch<React.SetStateAction<E>>;
|
||||
validate: (data?: T) => void;
|
||||
} {
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [errors, setErrors] = useState<E>({} as E);
|
||||
const validationTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const formDataRef = useRef<T>(formData);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { api } from "../api";
|
||||
import { invitesApi } from "../api";
|
||||
import { Header } from "../components/Header";
|
||||
import { useRequireAuth } from "../hooks/useRequireAuth";
|
||||
import { components } from "../generated/api";
|
||||
|
|
@ -29,7 +29,7 @@ export default function InvitesPage() {
|
|||
|
||||
const fetchInvites = useCallback(async () => {
|
||||
try {
|
||||
const data = await api.get<Invite[]>("/api/invites");
|
||||
const data = await invitesApi.getInvites();
|
||||
setInvites(data);
|
||||
} catch (err) {
|
||||
console.error("Failed to load invites:", err);
|
||||
|
|
|
|||
|
|
@ -53,6 +53,24 @@ vi.mock("../auth-context", () => ({
|
|||
},
|
||||
}));
|
||||
|
||||
// Mock profileApi
|
||||
const mockGetProfile = vi.fn();
|
||||
const mockUpdateProfile = vi.fn();
|
||||
|
||||
vi.mock("../api", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../api")>();
|
||||
// Create a getter that returns the mock functions
|
||||
return {
|
||||
...actual,
|
||||
get profileApi() {
|
||||
return {
|
||||
getProfile: mockGetProfile,
|
||||
updateProfile: mockUpdateProfile,
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Mock profile data
|
||||
const mockProfileData = {
|
||||
contact_email: "contact@example.com",
|
||||
|
|
@ -80,6 +98,9 @@ beforeEach(() => {
|
|||
mockHasPermission.mockImplementation(
|
||||
(permission: string) => mockUser?.permissions.includes(permission) ?? false
|
||||
);
|
||||
// Reset API mocks
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
mockUpdateProfile.mockResolvedValue(mockProfileData);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
|
@ -89,17 +110,14 @@ afterEach(() => {
|
|||
describe("ProfilePage - Display", () => {
|
||||
test("renders loading state initially", () => {
|
||||
mockIsLoading = true;
|
||||
vi.spyOn(global, "fetch").mockImplementation(() => new Promise(() => {}));
|
||||
mockGetProfile.mockImplementation(() => new Promise(() => {}));
|
||||
|
||||
render(<ProfilePage />);
|
||||
expect(screen.getByText("Loading...")).toBeDefined();
|
||||
});
|
||||
|
||||
test("renders profile page title", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
await waitFor(() => {
|
||||
|
|
@ -108,10 +126,7 @@ describe("ProfilePage - Display", () => {
|
|||
});
|
||||
|
||||
test("displays login email as read-only", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
await waitFor(() => {
|
||||
|
|
@ -122,10 +137,7 @@ describe("ProfilePage - Display", () => {
|
|||
});
|
||||
|
||||
test("shows read-only badge for login email", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
await waitFor(() => {
|
||||
|
|
@ -134,10 +146,7 @@ describe("ProfilePage - Display", () => {
|
|||
});
|
||||
|
||||
test("shows hint about login email", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
await waitFor(() => {
|
||||
|
|
@ -146,10 +155,7 @@ describe("ProfilePage - Display", () => {
|
|||
});
|
||||
|
||||
test("displays contact details section hint", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
await waitFor(() => {
|
||||
|
|
@ -158,10 +164,7 @@ describe("ProfilePage - Display", () => {
|
|||
});
|
||||
|
||||
test("displays fetched profile data", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
await waitFor(() => {
|
||||
|
|
@ -173,34 +176,22 @@ describe("ProfilePage - Display", () => {
|
|||
});
|
||||
|
||||
test("fetches profile with credentials", async () => {
|
||||
const fetchSpy = vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
"http://localhost:8000/api/profile",
|
||||
expect.objectContaining({
|
||||
credentials: "include",
|
||||
})
|
||||
);
|
||||
expect(mockGetProfile).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
test("displays empty fields when profile has null values", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
}),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
});
|
||||
|
||||
render(<ProfilePage />);
|
||||
await waitFor(() => {
|
||||
|
|
@ -213,10 +204,7 @@ describe("ProfilePage - Display", () => {
|
|||
|
||||
describe("ProfilePage - Navigation", () => {
|
||||
test("shows nav links for regular user", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
await waitFor(() => {
|
||||
|
|
@ -226,10 +214,7 @@ describe("ProfilePage - Navigation", () => {
|
|||
});
|
||||
|
||||
test("highlights My Profile in nav", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
await waitFor(() => {
|
||||
|
|
@ -273,13 +258,12 @@ describe("ProfilePage - Access Control", () => {
|
|||
roles: ["admin"],
|
||||
permissions: ["view_audit"],
|
||||
};
|
||||
const fetchSpy = vi.spyOn(global, "fetch");
|
||||
|
||||
render(<ProfilePage />);
|
||||
|
||||
// Give it a moment to potentially fetch
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
expect(mockGetProfile).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -304,10 +288,7 @@ describe("ProfilePage - Loading State", () => {
|
|||
|
||||
describe("ProfilePage - Form Behavior", () => {
|
||||
test("submit button is disabled when no changes", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
await waitFor(() => {
|
||||
|
|
@ -317,10 +298,7 @@ describe("ProfilePage - Form Behavior", () => {
|
|||
});
|
||||
|
||||
test("submit button is enabled after field changes", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockProfileData),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue(mockProfileData);
|
||||
|
||||
render(<ProfilePage />);
|
||||
|
||||
|
|
@ -338,16 +316,12 @@ describe("ProfilePage - Form Behavior", () => {
|
|||
});
|
||||
|
||||
test("auto-prepends @ to telegram when user starts with letter", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
}),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
});
|
||||
|
||||
render(<ProfilePage />);
|
||||
|
||||
|
|
@ -364,16 +338,12 @@ describe("ProfilePage - Form Behavior", () => {
|
|||
});
|
||||
|
||||
test("does not auto-prepend @ if user types @ first", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
}),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
});
|
||||
|
||||
render(<ProfilePage />);
|
||||
|
||||
|
|
@ -392,28 +362,25 @@ describe("ProfilePage - Form Behavior", () => {
|
|||
|
||||
describe("ProfilePage - Form Submission", () => {
|
||||
test("shows success toast after successful save", async () => {
|
||||
const fetchSpy = vi
|
||||
.spyOn(global, "fetch")
|
||||
mockGetProfile
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
}),
|
||||
} as Response)
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
contact_email: "new@example.com",
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
}),
|
||||
} as Response);
|
||||
contact_email: "new@example.com",
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
});
|
||||
mockUpdateProfile.mockResolvedValue({
|
||||
contact_email: "new@example.com",
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
});
|
||||
|
||||
render(<ProfilePage />);
|
||||
|
||||
|
|
@ -433,40 +400,33 @@ describe("ProfilePage - Form Submission", () => {
|
|||
expect(screen.getByText(/saved successfully/i)).toBeDefined();
|
||||
});
|
||||
|
||||
// Verify PUT was called
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
"http://localhost:8000/api/profile",
|
||||
expect.objectContaining({
|
||||
method: "PUT",
|
||||
credentials: "include",
|
||||
})
|
||||
);
|
||||
// Verify updateProfile was called
|
||||
expect(mockUpdateProfile).toHaveBeenCalledWith({
|
||||
contact_email: "new@example.com",
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("shows inline errors from backend validation", async () => {
|
||||
vi.spyOn(global, "fetch")
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
}),
|
||||
} as Response)
|
||||
.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 422,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
detail: {
|
||||
field_errors: {
|
||||
telegram: "Backend error: invalid handle",
|
||||
},
|
||||
},
|
||||
}),
|
||||
} as Response);
|
||||
mockGetProfile.mockResolvedValue({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
});
|
||||
// Import ApiError from the actual module (not mocked)
|
||||
const { ApiError } = await import("../api/client");
|
||||
mockUpdateProfile.mockRejectedValue(
|
||||
new ApiError("Validation failed", 422, {
|
||||
detail: {
|
||||
field_errors: {
|
||||
telegram: "Backend error: invalid handle",
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
render(<ProfilePage />);
|
||||
|
||||
|
|
@ -488,18 +448,13 @@ describe("ProfilePage - Form Submission", () => {
|
|||
});
|
||||
|
||||
test("shows error toast on network failure", async () => {
|
||||
vi.spyOn(global, "fetch")
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
}),
|
||||
} as Response)
|
||||
.mockRejectedValueOnce(new Error("Network error"));
|
||||
mockGetProfile.mockResolvedValue({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
});
|
||||
mockUpdateProfile.mockRejectedValue(new Error("Network error"));
|
||||
|
||||
render(<ProfilePage />);
|
||||
|
||||
|
|
@ -521,23 +476,28 @@ describe("ProfilePage - Form Submission", () => {
|
|||
});
|
||||
|
||||
test("submit button shows 'Saving...' while submitting", async () => {
|
||||
let resolveSubmit: (value: Response) => void;
|
||||
const submitPromise = new Promise<Response>((resolve) => {
|
||||
let resolveSubmit: (value: {
|
||||
contact_email: string | null;
|
||||
telegram: string | null;
|
||||
signal: string | null;
|
||||
nostr_npub: string | null;
|
||||
}) => void;
|
||||
const submitPromise = new Promise<{
|
||||
contact_email: string | null;
|
||||
telegram: string | null;
|
||||
signal: string | null;
|
||||
nostr_npub: string | null;
|
||||
}>((resolve) => {
|
||||
resolveSubmit = resolve;
|
||||
});
|
||||
|
||||
vi.spyOn(global, "fetch")
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
}),
|
||||
} as Response)
|
||||
.mockReturnValueOnce(submitPromise as Promise<Response>);
|
||||
mockGetProfile.mockResolvedValue({
|
||||
contact_email: null,
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
});
|
||||
mockUpdateProfile.mockReturnValue(submitPromise);
|
||||
|
||||
render(<ProfilePage />);
|
||||
|
||||
|
|
@ -559,15 +519,11 @@ describe("ProfilePage - Form Submission", () => {
|
|||
|
||||
// Resolve the promise
|
||||
resolveSubmit!({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
contact_email: "new@example.com",
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
}),
|
||||
} as Response);
|
||||
contact_email: "new@example.com",
|
||||
telegram: null,
|
||||
signal: null,
|
||||
nostr_npub: null,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole("button", { name: /save changes/i })).toBeDefined();
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
|
||||
import { api } from "../api";
|
||||
import { profileApi } from "../api";
|
||||
import { extractApiErrorMessage, extractFieldErrors } from "../utils/error-handling";
|
||||
import { Permission } from "../auth-context";
|
||||
import { Header } from "../components/Header";
|
||||
|
|
@ -81,7 +81,7 @@ export default function ProfilePage() {
|
|||
|
||||
const fetchProfile = useCallback(async () => {
|
||||
try {
|
||||
const data = await api.get<ProfileData>("/api/profile");
|
||||
const data = await profileApi.getProfile();
|
||||
const formValues = toFormData(data);
|
||||
setFormData(formValues);
|
||||
setOriginalData(formValues);
|
||||
|
|
@ -132,7 +132,7 @@ export default function ProfilePage() {
|
|||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
const data = await api.put<ProfileData>("/api/profile", {
|
||||
const data = await profileApi.updateProfile({
|
||||
contact_email: formData.contact_email || null,
|
||||
telegram: formData.telegram || null,
|
||||
signal: formData.signal || null,
|
||||
|
|
|
|||
|
|
@ -3,15 +3,9 @@
|
|||
import { useState, useEffect, useCallback, Suspense } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useAuth } from "../auth-context";
|
||||
import { api } from "../api";
|
||||
import { invitesApi } from "../api";
|
||||
import { authFormStyles as styles } from "../styles/auth-form";
|
||||
|
||||
interface InviteCheckResponse {
|
||||
valid: boolean;
|
||||
status?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
function SignupContent() {
|
||||
const searchParams = useSearchParams();
|
||||
const initialCode = searchParams.get("code") || "";
|
||||
|
|
@ -49,9 +43,7 @@ function SignupContent() {
|
|||
setInviteError("");
|
||||
|
||||
try {
|
||||
const response = await api.get<InviteCheckResponse>(
|
||||
`/api/invites/${encodeURIComponent(code.trim())}/check`
|
||||
);
|
||||
const response = await invitesApi.checkInvite(code.trim());
|
||||
|
||||
if (response.valid) {
|
||||
setInviteValid(true);
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
import { useEffect, useState, CSSProperties } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { Permission } from "../../auth-context";
|
||||
import { api } from "../../api";
|
||||
import { tradesApi } from "../../api";
|
||||
import { Header } from "../../components/Header";
|
||||
import { SatsDisplay } from "../../components/SatsDisplay";
|
||||
import { useRequireAuth } from "../../hooks/useRequireAuth";
|
||||
|
|
@ -42,7 +42,7 @@ export default function TradeDetailPage() {
|
|||
try {
|
||||
setIsLoadingTrade(true);
|
||||
setError(null);
|
||||
const data = await api.get<ExchangeResponse>(`/api/trades/${publicId}`);
|
||||
const data = await tradesApi.getTrade(publicId);
|
||||
setTrade(data);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch trade:", err);
|
||||
|
|
@ -221,7 +221,7 @@ export default function TradeDetailPage() {
|
|||
return;
|
||||
}
|
||||
try {
|
||||
await api.post(`/api/trades/${trade.public_id}/cancel`, {});
|
||||
await tradesApi.cancelTrade(trade.public_id);
|
||||
router.push("/trades");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to cancel trade");
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
import { useEffect, useState, useCallback, CSSProperties } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Permission } from "../auth-context";
|
||||
import { api } from "../api";
|
||||
import { tradesApi } from "../api";
|
||||
import { Header } from "../components/Header";
|
||||
import { SatsDisplay } from "../components/SatsDisplay";
|
||||
import { LoadingState } from "../components/LoadingState";
|
||||
|
|
@ -37,7 +37,7 @@ export default function TradesPage() {
|
|||
|
||||
const fetchTrades = useCallback(async () => {
|
||||
try {
|
||||
const data = await api.get<ExchangeResponse[]>("/api/trades");
|
||||
const data = await tradesApi.getTrades();
|
||||
setTrades(data);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch trades:", err);
|
||||
|
|
@ -58,7 +58,7 @@ export default function TradesPage() {
|
|||
setError(null);
|
||||
|
||||
try {
|
||||
await api.post<ExchangeResponse>(`/api/trades/${publicId}/cancel`, {});
|
||||
await tradesApi.cancelTrade(publicId);
|
||||
await fetchTrades();
|
||||
setConfirmCancelId(null);
|
||||
} catch (err) {
|
||||
|
|
|
|||
|
|
@ -98,7 +98,7 @@ export function validateNostrNpub(value: string): string | undefined {
|
|||
/**
|
||||
* Field errors object type.
|
||||
*/
|
||||
export interface FieldErrors {
|
||||
export interface FieldErrors extends Record<string, string | undefined> {
|
||||
contact_email?: string;
|
||||
telegram?: string;
|
||||
signal?: string;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue