aboutsummaryrefslogtreecommitdiff
path: root/public/js/Fetcher.js
blob: 0f56628322c8956fbe6ee1c6cdd26eebd5fc57e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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 };
		}
	}
}