types and api client
This commit is contained in:
79
frontend/src/lib/api.ts
Normal file
79
frontend/src/lib/api.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import type {
|
||||
CategoryListResponse,
|
||||
Pattern,
|
||||
PatternListResponse,
|
||||
QuestionDetail,
|
||||
QuestionListResponse,
|
||||
Stats,
|
||||
} from "@/types";
|
||||
|
||||
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";
|
||||
|
||||
async function fetchApi<T>(
|
||||
endpoint: string,
|
||||
options?: RequestInit
|
||||
): Promise<T> {
|
||||
const url = `${API_BASE_URL}${endpoint}`;
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options?.headers,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export interface QuestionFilters {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
difficulty?: string;
|
||||
category?: string;
|
||||
pattern?: string;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
export async function getQuestions(
|
||||
filters: QuestionFilters = {}
|
||||
): Promise<QuestionListResponse> {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (filters.page) params.set("page", filters.page.toString());
|
||||
if (filters.limit) params.set("limit", filters.limit.toString());
|
||||
if (filters.difficulty) params.set("difficulty", filters.difficulty);
|
||||
if (filters.category) params.set("category", filters.category);
|
||||
if (filters.pattern) params.set("pattern", filters.pattern);
|
||||
if (filters.search) params.set("search", filters.search);
|
||||
|
||||
const queryString = params.toString();
|
||||
const endpoint = queryString
|
||||
? `/api/questions?${queryString}`
|
||||
: "/api/questions";
|
||||
|
||||
return fetchApi<QuestionListResponse>(endpoint);
|
||||
}
|
||||
|
||||
export async function getQuestion(slug: string): Promise<QuestionDetail> {
|
||||
return fetchApi<QuestionDetail>(`/api/questions/${slug}`);
|
||||
}
|
||||
|
||||
export async function getCategories(): Promise<CategoryListResponse> {
|
||||
return fetchApi<CategoryListResponse>("/api/categories");
|
||||
}
|
||||
|
||||
export async function getPatterns(): Promise<PatternListResponse> {
|
||||
return fetchApi<PatternListResponse>("/api/patterns");
|
||||
}
|
||||
|
||||
export async function getPattern(slug: string): Promise<Pattern> {
|
||||
return fetchApi<Pattern>(`/api/patterns/${slug}`);
|
||||
}
|
||||
|
||||
export async function getStats(): Promise<Stats> {
|
||||
return fetchApi<Stats>("/api/stats");
|
||||
}
|
||||
Reference in New Issue
Block a user