From bce9fda51d334a547ec5a48f0b7699ed3b5d7944 Mon Sep 17 00:00:00 2001 From: polo Date: Wed, 29 Oct 2025 21:42:39 +0100 Subject: =?UTF-8?q?classe=20Fetcher,=20gestion=20r=C3=A9seaux=20sociaux=20?= =?UTF-8?q?pr=C3=A9sents/absents,=20partie=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/js/Fetcher.js | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 public/js/Fetcher.js (limited to 'public/js/Fetcher.js') diff --git a/public/js/Fetcher.js b/public/js/Fetcher.js new file mode 100644 index 0000000..0f56628 --- /dev/null +++ b/public/js/Fetcher.js @@ -0,0 +1,51 @@ +class Fetcher{ + constructor(options = {}) { + this.endpoint = options.endpoint || 'index.php'; + this.method = options.method || 'POST'; // normalement c'est GET par défaut + + // Callbacks optionnels + this.onSuccess = options.onSuccess || null; + this.onFailure = options.onFailure || null; + //this.onError = options.onError || null; // Pour les erreurs réseau/parsing + } + + send(body){ + const options = { method: this.method }; + + if(this.method !== 'GET'){ // si GET, ni body ni headers + if(body instanceof FormData){ // pas de headers + options.body = body; + } + else if(body !== null && typeof body === 'object'){ // objet => json + options.headers = { 'Content-Type': 'application/json' }; + options.body = JSON.stringify(body); + } + else{ // blob? + options.body = body; + } + } + + return fetch(this.endpoint, options) + .then(response => response.json()) + .then(data => this.onResponse(data)) + .catch(error => { + console.error('Erreur:', error); + }); + } + + onResponse(data){ + if(data.success){ + if(this.onSuccess){ + this.onSuccess(data); + } + return{ success: true, data }; + } + else{ + if(this.onFailure){ + this.onFailure(data); + } + console.error(data.message || "Erreur serveur"); + return { success: false, data }; + } + } +} \ No newline at end of file -- cgit v1.2.3