fp/services/next/app/lib/fetch-api.ts

35 lines
991 B
TypeScript
Raw Normal View History

2024-01-20 16:16:14 +00:00
// greets https://github.com/strapi/nextjs-corporate-starter/blob/main/frontend/src/app/%5Blang%5D/utils/fetch-api.tsx#L4
import qs from "qs";
2024-11-05 19:48:21 +00:00
import { postgrestLocalUrl, strapiUrl } from "./constants";
2024-01-20 16:16:14 +00:00
export default async function fetchAPI(
path: string,
urlParamsObject = {},
options = {}
) {
try {
// Merge default and user options
const mergedOptions = {
next: { revalidate: 60 },
headers: {
"Content-Type": "application/json",
},
...options,
};
// Build request URL
const queryString = qs.stringify(urlParamsObject);
2024-11-05 19:48:21 +00:00
const requestUrl = `${postgrestLocalUrl}${path}${queryString ? `?${queryString}` : ""}`;
console.log(`fetching--> ${requestUrl}`)
2024-01-20 16:16:14 +00:00
// Trigger API call
const response = await fetch(requestUrl, mergedOptions);
const data = await response.json();
return data;
} catch (error) {
console.error(error);
2024-05-27 22:20:58 +00:00
throw new Error(`Error while fetching data from API. ${path}`);
2024-01-20 16:16:14 +00:00
}
}