mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
1b37ff65f5
Gate administration actions by role permissions, centralize cached session access for data fetching, and return forbidden responses for unauthorized pages. Also lazy-load user exports and adjust search field sizing.
116 lines
4.1 KiB
TypeScript
116 lines
4.1 KiB
TypeScript
import { redirect } from "next/navigation"
|
|
import { ResponseData } from "@/types/types"
|
|
import { logger } from "./logger"
|
|
import { getCacheServerSession } from "./get-access-data"
|
|
|
|
export default async function fetchData(url: string = '/', cache: "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload" = 'default', next?: NextFetchRequestConfig) {
|
|
const { BASE_URL_API } = process.env
|
|
const session = await getCacheServerSession()
|
|
|
|
const res = await fetch(BASE_URL_API + url, {
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${session?.user.access_token}`,
|
|
},
|
|
cache: cache,
|
|
next: next
|
|
})
|
|
|
|
const data: ResponseData = await res.json()
|
|
|
|
// Recommendation: handle errors
|
|
if (!res.ok) {
|
|
logger.error(`ERROR FETCH DATA. http error: ${JSON.stringify(res)}. detail error: ${data}`);
|
|
|
|
console.log("FETCH ERROR DATA :", res.status, data)
|
|
if (res.status === 401 || res.status === 403) return redirect(`/auth?error=Session error or has expired !`)
|
|
// This will activate the closest `error.js` Error Boundary
|
|
throw new Error(`(${data.code || res.status}) ${data.message || res.statusText}`)
|
|
}
|
|
|
|
return data.data
|
|
}
|
|
|
|
export async function fetchDataWithPost(url: string = '/', payload: any = {}, cache: "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload" = 'default', next?: NextFetchRequestConfig) {
|
|
const { BASE_URL_API } = process.env
|
|
const session = await getCacheServerSession()
|
|
|
|
const res = await fetch(BASE_URL_API + url, {
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${session?.user.access_token}`,
|
|
},
|
|
method: 'POST',
|
|
cache: cache,
|
|
next: next,
|
|
body: JSON.stringify(payload)
|
|
})
|
|
|
|
// Read raw body once
|
|
const raw = await res.text();
|
|
|
|
// Try parse as JSON if possible
|
|
let data: any;
|
|
try {
|
|
data = raw ? JSON.parse(raw) : {};
|
|
} catch {
|
|
data = { message: raw };
|
|
}
|
|
|
|
if (!res.ok) {
|
|
logger.error(`ERROR FETCH DATA. http error: ${JSON.stringify(res)}. detail error: ${data}`);
|
|
|
|
console.log("FETCH ERROR DATA :", res.status, data)
|
|
if (res.status === 401 || res.status === 403) redirect(`/auth?error=Session error or has expired !`);
|
|
|
|
throw new Error(`(${data?.code || res.status} ${res.statusText}) ${data?.message}`);
|
|
}
|
|
|
|
return data.data
|
|
}
|
|
|
|
type PageSearchParams = {
|
|
[key: string]: string | undefined;
|
|
}
|
|
|
|
export async function getQueryStringFilteredAssignments(searchParams: PageSearchParams) {
|
|
const apiParams = new URLSearchParams();
|
|
|
|
// Helper function to safely map and append values if they exist
|
|
const appendIfPresent = (nextJsKey: string, backendApiKey: string) => {
|
|
const value = searchParams[nextJsKey];
|
|
if (value) {
|
|
// const stringValue = Array.isArray(value) ? value.join(',') : value;
|
|
// apiParams.append(backendApiKey, stringValue);
|
|
|
|
value.split(',').forEach(v => {
|
|
if (v.trim()) apiParams.append(backendApiKey, v.trim())
|
|
})
|
|
}
|
|
};
|
|
|
|
// --- 1. Map IDs ---
|
|
// appendIfPresent('client', 'client_id');
|
|
// appendIfPresent('end_user', 'end_user_id');
|
|
appendIfPresent('status', 'project_assignment_status_id');
|
|
appendIfPresent('users', 'user_id');
|
|
|
|
// --- 2. Map Dates (Project) ---
|
|
appendIfPresent('project_date_from', 'project_start_date');
|
|
appendIfPresent('project_date_to', 'project_end_date');
|
|
|
|
// --- 3. Map Dates (Work Order) ---
|
|
appendIfPresent('wo_date_from', 'wo_start_date');
|
|
appendIfPresent('wo_date_to', 'wo_end_date');
|
|
|
|
// --- 4. Map Dates (Internal Memo) ---
|
|
appendIfPresent('im_date_from', 'im_start_date');
|
|
appendIfPresent('im_date_to', 'im_end_date');
|
|
|
|
// Construct the final URL.
|
|
// If no params exist, apiParams.toString() is empty, so we safely handle the '?'
|
|
const queryString = apiParams.toString();
|
|
// const finalUrl = queryString ? `${baseUrl}?${queryString}` : baseUrl;
|
|
|
|
return queryString
|
|
} |