84 lines
1.9 KiB
TypeScript
84 lines
1.9 KiB
TypeScript
import { cookies } from "next/headers";
|
|
|
|
import {
|
|
AuditApiResponse,
|
|
AuditQueryResult,
|
|
DEFAULT_PAGE_SIZE,
|
|
extractArray,
|
|
normalizeRows,
|
|
resolveTotal,
|
|
} from "@/app/dashboard/audits/auditTransforms";
|
|
import {
|
|
AUDIT_CACHE_TAG,
|
|
AUTH_COOKIE_NAME,
|
|
BE_BASE_URL,
|
|
REVALIDATE_SECONDS,
|
|
} from "./constants";
|
|
|
|
interface FetchAuditsParams {
|
|
limit?: number;
|
|
page?: number;
|
|
sort?: string;
|
|
filter?: string;
|
|
entity?: string;
|
|
}
|
|
|
|
export async function fetchAudits({
|
|
limit = DEFAULT_PAGE_SIZE,
|
|
page = 1,
|
|
sort,
|
|
filter,
|
|
entity,
|
|
}: FetchAuditsParams = {}): Promise<AuditQueryResult> {
|
|
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));
|
|
if (sort) params.set("sort", sort);
|
|
if (filter) params.set("filter", filter);
|
|
if (entity) params.set("Entity", entity);
|
|
|
|
const backendUrl = `${BE_BASE_URL}/api/v1/audit${
|
|
params.size ? `?${params.toString()}` : ""
|
|
}`;
|
|
|
|
const response = await fetch(backendUrl, {
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
next: {
|
|
revalidate: REVALIDATE_SECONDS,
|
|
tags: [AUDIT_CACHE_TAG],
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response
|
|
.json()
|
|
.catch(() => ({ message: "Failed to fetch audits" }));
|
|
throw new Error(errorData?.message || "Failed to fetch audits");
|
|
}
|
|
|
|
const payload = (await response.json()) as AuditApiResponse;
|
|
const pageIndex = page - 1;
|
|
const auditEntries = extractArray(payload);
|
|
const rows = normalizeRows(auditEntries, pageIndex);
|
|
const total = resolveTotal(payload, rows.length);
|
|
|
|
return {
|
|
rows,
|
|
total,
|
|
payload,
|
|
pageIndex,
|
|
};
|
|
}
|