Files
goGin/frontend/services/userService.ts
Beyhan Oğur 2a5b661443 first commit
2026-04-26 21:46:42 +03:00

65 lines
2.0 KiB
TypeScript

import { UserListResponse, UserPayload, UserResponse } from "@/types/user";
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8080";
async function fetchWithAuth(url: string, token: string, options: RequestInit = {}) {
const headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
...options.headers,
};
const response = await fetch(`${API_URL}${url}`, {
...options,
headers,
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || "API request failed");
}
// For 204 No Content
if (response.status === 204) {
return null;
}
return response.json();
}
export const userService = {
async getUsers(token: string, page: number = 1, per_page: number = 20, soft: string = ""): Promise<UserListResponse> {
const queryParams = new URLSearchParams({
page: page.toString(),
per_page: per_page.toString(),
});
if (soft) {
queryParams.append("soft", soft);
}
return fetchWithAuth(`/api/v1/admin/users?${queryParams.toString()}`, token);
},
async getUser(token: string, id: number): Promise<UserResponse> {
return fetchWithAuth(`/api/v1/admin/users/${id}`, token);
},
async updateUser(token: string, id: number, data: UserPayload): Promise<UserResponse> {
return fetchWithAuth(`/api/v1/admin/users/${id}`, token, {
method: "PUT",
body: JSON.stringify(data),
});
},
async deleteUser(token: string, id: number): Promise<void> {
return fetchWithAuth(`/api/v1/admin/users/${id}`, token, {
method: "DELETE",
});
},
async restoreUser(token: string, id: number): Promise<UserResponse> {
return fetchWithAuth(`/api/v1/admin/users/${id}/restore`, token, {
method: "POST",
});
},
};