designtopack/src/stores/api.js

180 lines
4.8 KiB
JavaScript

import { defineStore } from "pinia";
import uniqid from "uniqid";
export const useApiStore = defineStore("api", () => {
/**
* 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
* fetchData().then(data => {
* console.log(data);
* }).catch(error => {
* console.error('Error fetching data:', error);
* });
*
* @example
* // Fetch data for a specific path
* fetchData('/about').then(data => {
* console.log(data);
* }).catch(error => {
* console.error('Error fetching data:', error);
* });
*/
async function fetchData(path = window.location.pathname) {
const isHomePage = path === "/";
path = path === "/" ? "/home" : path;
path = path.startsWith("/") ? path : "/" + path;
path = path.endsWith("/") ? path.substring(0, path.length - 1) : path;
const url = `${window.location.origin}${path}.json`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("Données récupérées du chemin " + path, data);
return data;
} catch (error) {
console.error(
"Une erreur s'est produite lors de la récupération des données pour l'URL :",
url,
error
);
throw error;
}
}
function fetchDataThroughKQL() {
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);
});
}
async function fetchRoute(path, method, data) {
const config = {
method: method,
};
if (data) {
config.body = JSON.stringify(data);
}
try {
const response = await fetch(path, config);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("La route " + path + " a fonctionné.");
return data;
} catch (error) {
console.error("La route " + path + " n'a pas fonctionné.", error);
throw error;
}
}
async function addComment(comment) {
const headers = {
method: "POST",
body: JSON.stringify(comment),
};
try {
const response = await fetch("/create-comment.json", headers);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const newFile = await response.json();
return newFile;
} catch (error) {
console.error(
"Une erreur s'est produite lors de l'ajout du commentaire :",
commentaire,
error
);
throw error;
}
}
async function readNotification(userUuid, group, notificationId) {
const headers = {
method: "POST",
body: JSON.stringify({
userUuid,
notificationId,
group,
}),
};
try {
const response = await fetch("/mark-as-read.json", headers);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const newNotifications = await response.json();
return newNotifications;
} catch (error) {
console.error(
"Une erreur s'est produite lors de la lecture de la notification n°",
notificationId,
error
);
throw error;
}
}
return {
fetchDataThroughKQL,
fetchData,
fetchRoute,
addComment,
readNotification,
};
});