designtopack/src/stores/api.js

100 lines
2.8 KiB
JavaScript
Raw Normal View History

2024-07-10 18:43:46 +02:00
import { defineStore } from "pinia";
export const useApiStore = defineStore("counter", () => {
2024-09-04 11:28:12 +02:00
/**
* Asynchronously fetches JSON data corresponding to a given path.
*
* @param {string} [path=window.location.pathname] - The path for which to fetch data.
* - If no path is provided, the function will use the current page's path.
* - If the path is "/", it is assumed to be the homepage, and "home.json" is fetched.
* - For other paths, the function will append ".json" to the path and fetch that URL.
*
* @returns {Promise<Object>} A promise that resolves to the JSON data if the fetch is successful.
*
* @throws {Error} Will throw an error if the HTTP request fails (e.g., non-200 status code).
* - The error will include the HTTP status code and a message indicating the fetch failed.
*
* @example
* // Fetch data for the current page
* fetchPageData().then(data => {
* console.log(data);
* }).catch(error => {
* console.error('Error fetching data:', error);
* });
*
* @example
* // Fetch data for a specific path
* fetchPageData('/about').then(data => {
* console.log(data);
* }).catch(error => {
* console.error('Error fetching data:', error);
* });
*/
async function fetchPageData(path = window.location.pathname) {
const isHomePage = path === "/";
2024-07-11 12:42:29 +02:00
const url = isHomePage
2024-09-04 11:28:12 +02:00
? `${window.location.origin}/home.json`
: `${window.location.origin}/${path}.json`;
2024-07-11 12:42:29 +02:00
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
2024-09-04 11:28:12 +02:00
console.log("Données récupérées du chemin " + path, data);
2024-07-11 12:42:29 +02:00
return data;
} catch (error) {
console.error(
2024-09-04 11:28:12 +02:00
"Une erreur s'est produite lors de la récupération des données pour l'URL :",
url,
2024-07-11 12:42:29 +02:00
error
);
throw error;
}
}
function fetchDataThroughKQL() {
2024-07-10 18:43:46 +02:00
const api = "/api/query";
const username = import.meta.env.VITE_USERNAME;
const password = import.meta.env.VITE_PASSWORD;
const token = btoa(`${username}:${password}`);
const headers = {
Authorization: `Basic ${token}`,
};
const request = {
method: "post",
body: JSON.stringify({
query: `page('home')`,
select: {
testImages: {
query: "page.testImages.toFiles",
select: {
url: true,
},
},
blocks: {
query: "page.testBlocks.toBlocks",
},
},
}),
headers,
};
fetch(api, request)
.then((response) => response.json())
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
2024-07-11 12:42:29 +02:00
return { fetchDataThroughKQL, fetchPageData };
2024-07-10 18:43:46 +02:00
});