62 lines
1.4 KiB
TypeScript
62 lines
1.4 KiB
TypeScript
import { cookies } from "next/headers";
|
|
|
|
import { IUser } from "@/app/features/Pages/Admin/Users/interfaces";
|
|
import {
|
|
AUTH_COOKIE_NAME,
|
|
BE_BASE_URL,
|
|
REVALIDATE_SECONDS,
|
|
USERS_CACHE_TAG,
|
|
} from "./constants";
|
|
|
|
const DEFAULT_PAGE_SIZE = 25;
|
|
|
|
interface FetchUsersParams {
|
|
limit?: number;
|
|
page?: number;
|
|
}
|
|
|
|
export async function fetchUsers({
|
|
limit = DEFAULT_PAGE_SIZE,
|
|
page = 1,
|
|
}: FetchUsersParams = {}): Promise<IUser[]> {
|
|
const cookieStore = await cookies();
|
|
const token = cookieStore.get(AUTH_COOKIE_NAME)?.value;
|
|
|
|
if (!token) {
|
|
throw new Error("Missing auth token");
|
|
}
|
|
|
|
const params = new URLSearchParams();
|
|
params.set("limit", String(limit));
|
|
params.set("page", String(page));
|
|
|
|
const backendUrl = `${BE_BASE_URL}/api/v1/users${
|
|
params.size ? `?${params.toString()}` : ""
|
|
}`;
|
|
console.log("[Users] - backendUrl", backendUrl);
|
|
const response = await fetch(backendUrl, {
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
next: {
|
|
revalidate: REVALIDATE_SECONDS,
|
|
tags: [USERS_CACHE_TAG],
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response
|
|
.json()
|
|
.catch(() => ({ message: "Failed to fetch users" }));
|
|
throw new Error(errorData?.message || "Failed to fetch users");
|
|
}
|
|
|
|
const data = await response.json();
|
|
|
|
const users = Array.isArray(data) ? data : data.users || data.data || [];
|
|
|
|
return users;
|
|
}
|