72 lines
1.8 KiB
TypeScript
72 lines
1.8 KiB
TypeScript
"use server";
|
|
|
|
import { cookies } from "next/headers";
|
|
import {
|
|
AUTH_COOKIE_NAME,
|
|
BE_BASE_URL,
|
|
REVALIDATE_SECONDS,
|
|
getAdminResourceCacheTag,
|
|
} from "./constants";
|
|
import { buildFilterParam } from "@/app/api/dashboard/admin/utils";
|
|
|
|
export interface IFetchAdminResourceParams {
|
|
resource: string;
|
|
filters?: Record<string, unknown>;
|
|
pagination?: { page: number; limit: number };
|
|
sort?: { field: string; order: "asc" | "desc" };
|
|
}
|
|
|
|
export async function fetchAdminResource({
|
|
resource,
|
|
filters = {},
|
|
pagination = { page: 1, limit: 100 },
|
|
sort,
|
|
}: IFetchAdminResourceParams) {
|
|
const cookieStore = await cookies();
|
|
const token = cookieStore.get(AUTH_COOKIE_NAME)?.value;
|
|
|
|
if (!token) {
|
|
throw new Error("Missing auth token");
|
|
}
|
|
|
|
const queryParams = new URLSearchParams();
|
|
queryParams.set("limit", String(pagination.limit ?? 100));
|
|
queryParams.set("page", String(pagination.page ?? 1));
|
|
|
|
if (sort?.field && sort?.order) {
|
|
queryParams.set("sort", `${sort.field}:${sort.order}`);
|
|
}
|
|
|
|
const filterParam = buildFilterParam(
|
|
filters as Record<string, string | { operator?: string; value: string }>
|
|
);
|
|
if (filterParam) {
|
|
queryParams.set("filter", filterParam);
|
|
}
|
|
|
|
const backendUrl = `${BE_BASE_URL}/api/v1/${resource}${
|
|
queryParams.size ? `?${queryParams.toString()}` : ""
|
|
}`;
|
|
|
|
const response = await fetch(backendUrl, {
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
next: {
|
|
revalidate: REVALIDATE_SECONDS,
|
|
tags: [getAdminResourceCacheTag(resource)],
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response
|
|
.json()
|
|
.catch(() => ({ message: `Failed to fetch ${resource}` }));
|
|
throw new Error(errorData?.message || `Failed to fetch ${resource}`);
|
|
}
|
|
|
|
return response.json();
|
|
}
|