diff options
Diffstat (limited to 'public/js/Fetcher.js')
| -rw-r--r-- | public/js/Fetcher.js | 51 |
1 files changed, 51 insertions, 0 deletions
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 @@ | |||
| 1 | class Fetcher{ | ||
| 2 | constructor(options = {}) { | ||
| 3 | this.endpoint = options.endpoint || 'index.php'; | ||
| 4 | this.method = options.method || 'POST'; // normalement c'est GET par défaut | ||
| 5 | |||
| 6 | // Callbacks optionnels | ||
| 7 | this.onSuccess = options.onSuccess || null; | ||
| 8 | this.onFailure = options.onFailure || null; | ||
| 9 | //this.onError = options.onError || null; // Pour les erreurs réseau/parsing | ||
| 10 | } | ||
| 11 | |||
| 12 | send(body){ | ||
| 13 | const options = { method: this.method }; | ||
| 14 | |||
| 15 | if(this.method !== 'GET'){ // si GET, ni body ni headers | ||
| 16 | if(body instanceof FormData){ // pas de headers | ||
| 17 | options.body = body; | ||
| 18 | } | ||
| 19 | else if(body !== null && typeof body === 'object'){ // objet => json | ||
| 20 | options.headers = { 'Content-Type': 'application/json' }; | ||
| 21 | options.body = JSON.stringify(body); | ||
| 22 | } | ||
| 23 | else{ // blob? | ||
| 24 | options.body = body; | ||
| 25 | } | ||
| 26 | } | ||
| 27 | |||
| 28 | return fetch(this.endpoint, options) | ||
| 29 | .then(response => response.json()) | ||
| 30 | .then(data => this.onResponse(data)) | ||
| 31 | .catch(error => { | ||
| 32 | console.error('Erreur:', error); | ||
| 33 | }); | ||
| 34 | } | ||
| 35 | |||
| 36 | onResponse(data){ | ||
| 37 | if(data.success){ | ||
| 38 | if(this.onSuccess){ | ||
| 39 | this.onSuccess(data); | ||
| 40 | } | ||
| 41 | return{ success: true, data }; | ||
| 42 | } | ||
| 43 | else{ | ||
| 44 | if(this.onFailure){ | ||
| 45 | this.onFailure(data); | ||
| 46 | } | ||
| 47 | console.error(data.message || "Erreur serveur"); | ||
| 48 | return { success: false, data }; | ||
| 49 | } | ||
| 50 | } | ||
| 51 | } \ No newline at end of file | ||
