| 1 | const API_BASE_URL = (() => { |
| 2 | const path = window.location.pathname; |
| 3 | const sameOrigin = path === '/' || path === '/index.html' || path.startsWith('/api'); |
| 4 | if (sameOrigin) { |
| 5 | return `${window.location.origin}/api`; |
| 6 | } |
| 7 | return 'http://localhost:8080/api'; |
| 8 | })(); |
| 9 | |
| 10 | const API = { |
| 11 | async request(endpoint, options = {}) { |
| 12 | const url = `${API_BASE_URL}${endpoint}`; |
| 13 | const token = localStorage.getItem('token'); |
| 14 | |
| 15 | const config = { |
| 16 | headers: { |
| 17 | 'Content-Type': 'application/json', |
| 18 | ...(token && { Authorization: `Bearer ${token}` }) |
| 19 | }, |
| 20 | ...options |
| 21 | }; |
| 22 | |
| 23 | const response = await fetch(url, config); |
| 24 | const body = await response.json().catch(() => null); |
| 25 | |
| 26 | if (!response.ok) { |
| 27 | if (response.status === 401 || response.status === 403) { |
| 28 | localStorage.removeItem('token'); |
| 29 | localStorage.removeItem('user'); |
| 30 | const path = window.location.pathname; |
| 31 | if (!path.endsWith('login.html') && !path.endsWith('index.html') && !path.endsWith('registro.html')) { |
| 32 | const prefix = path.includes('/pages/') ? '../' : ''; |
| 33 | window.location.href = `${prefix}login.html`; |
| 34 | } |
| 35 | throw new Error(body?.message || 'Sesión expirada o sin autorización. Vuelve a iniciar sesión.'); |
| 36 | } |
| 37 | const error = new Error(body?.message || `Error ${response.status}`); |
| 38 | error.status = response.status; |
| 39 | error.data = body && body.data !== undefined ? body.data : body; |
| 40 | throw error; |
| 41 | } |
| 42 | |
| 43 | return body && body.data !== undefined ? body.data : body; |
| 44 | } |
| 45 | }; |