mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:46:29 +00:00
aa99536a32
Use BASE_URL_API_LOCAL_SERVER for server-side data requests and load the layout session through the cached helper. Update production URLs to HTTPS and use 127.0.0.1 for local API endpoints.
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 baseUrl = process.env.BASE_URL_API_LOCAL_SERVER
|
|
const session = await getCacheServerSession()
|
|
|
|
const res = await fetch(baseUrl + 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 baseUrl = process.env.BASE_URL_API_LOCAL_SERVER
|
|
const session = await getCacheServerSession()
|
|
|
|
const res = await fetch(baseUrl + 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
|
|
} |