Files
hats-app/lib/fetchData.ts
T
Ichsan Kurniawan d10603acc8 Optimize Next.js memory and handle 404s
Configure startup and package-import optimizations, exclude generated Next.js files from TypeScript checks, and route fetch responses with status 404 to the not-found page.
2026-11-18 18:20:27 +07:00

118 lines
4.2 KiB
TypeScript

import { notFound, 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 !`)
if (res.status === 404) notFound()
// 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 !`);
if (res.status === 404) notFound()
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
}