utils.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * Utilitaires communs : appels API, affichage erreurs.
  3. */
  4. const API_BASE = '/api';
  5. async function apiGet(path, params = {}) {
  6. const url = new URL(API_BASE + path, window.location.origin);
  7. Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
  8. const res = await fetch(url.toString());
  9. const data = await res.json().catch(() => ({}));
  10. if (!res.ok) {
  11. throw new Error(data.error || 'Erreur API');
  12. }
  13. return data;
  14. }
  15. async function apiPost(path, body) {
  16. const res = await fetch(API_BASE + path, {
  17. method: 'POST',
  18. headers: { 'Content-Type': 'application/json' },
  19. body: JSON.stringify(body),
  20. });
  21. const data = await res.json().catch(() => ({}));
  22. if (!res.ok) {
  23. throw new Error(data.error || 'Erreur API');
  24. }
  25. return data;
  26. }
  27. async function apiPut(path, body) {
  28. const res = await fetch(API_BASE + path, {
  29. method: 'PUT',
  30. headers: { 'Content-Type': 'application/json' },
  31. body: JSON.stringify(body),
  32. });
  33. const data = await res.json().catch(() => ({}));
  34. if (!res.ok) {
  35. throw new Error(data.error || 'Erreur API');
  36. }
  37. return data;
  38. }
  39. async function apiDelete(path) {
  40. const res = await fetch(API_BASE + path, {
  41. method: 'DELETE',
  42. });
  43. const data = await res.json().catch(() => ({}));
  44. if (!res.ok) {
  45. throw new Error(data.error || 'Erreur API');
  46. }
  47. return data;
  48. }
  49. function showError(message) {
  50. const el = document.getElementById('error-message');
  51. if (el) {
  52. el.textContent = message;
  53. el.classList.remove('hidden');
  54. } else {
  55. alert(message);
  56. }
  57. }
  58. function hideError() {
  59. const el = document.getElementById('error-message');
  60. if (el) {
  61. el.classList.add('hidden');
  62. el.textContent = '';
  63. }
  64. }
  65. function formatMoney(value) {
  66. return new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(value);
  67. }
  68. function formatDate(str) {
  69. if (!str) return '-';
  70. const d = new Date(str);
  71. return isNaN(d.getTime()) ? str : d.toLocaleDateString('fr-FR');
  72. }
  73. function formatNumber(value) {
  74. if (value == null) return '-';
  75. return new Intl.NumberFormat('fr-FR').format(value);
  76. }