mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
66 lines
2.3 KiB
TypeScript
66 lines
2.3 KiB
TypeScript
import { getServerSession } from "next-auth"
|
|
import { authOptions } from "@/pages/api/auth/[...nextauth]"
|
|
import { redirect } from "next/navigation"
|
|
import { ResponseData } from "@/types/types"
|
|
|
|
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 getServerSession(authOptions)
|
|
|
|
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) {
|
|
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 getServerSession(authOptions)
|
|
|
|
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) {
|
|
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
|
|
} |