#28 refactor(api): using axios instead fetch.
This commit is contained in:
@@ -1,36 +1,17 @@
|
||||
import AuthService from '@/services/auth';
|
||||
import http from '@/services/http';
|
||||
|
||||
class DjangoApi {
|
||||
constructor() {
|
||||
this.base = import.meta.env.VITE_DJANGO_BASE_URL;
|
||||
}
|
||||
|
||||
_authHeaders() {
|
||||
const token = AuthService.getAccessToken();
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
getRequest(url) {
|
||||
return http.get(url).then(r => r.data);
|
||||
}
|
||||
|
||||
_handleResponse(response) {
|
||||
if (!response.ok) {
|
||||
// Si el token ha expirado (401) intentamos refrescar y re‑intentar
|
||||
if (response.status === 401) {
|
||||
return AuthService.refresh().then(newToken => {
|
||||
// volver a ejecutar la petición original con el nuevo token
|
||||
const retryHeaders = {
|
||||
...response.headers,
|
||||
Authorization: `Bearer ${newToken}`,
|
||||
};
|
||||
// aquí usamos fetch de nuevo con los mismos parámetros
|
||||
// (para simplificar, delegamos a getRequest/postRequest)
|
||||
// En la práctica, extrae la lógica a una función reutilizable.
|
||||
throw new Error('Retry logic should be implemented here');
|
||||
});
|
||||
}
|
||||
return response.json().then(err => {
|
||||
throw new Error(`Error ${response.status}: ${err.detail || response.statusText}`);
|
||||
});
|
||||
}
|
||||
return response.json();
|
||||
postRequest(url, payload) {
|
||||
return http.post(url, payload).then(r => r.data);
|
||||
}
|
||||
|
||||
getCustomers() {
|
||||
@@ -107,26 +88,6 @@ class DjangoApi {
|
||||
const url = this.base + '/don_confiao/api/enviar_ventas_a_tryton';
|
||||
return this.postRequest(url, {});
|
||||
}
|
||||
|
||||
getRequest(url) {
|
||||
return fetch(url, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...this._authHeaders(),
|
||||
},
|
||||
}).then(this._handleResponse);
|
||||
}
|
||||
|
||||
postRequest(url, content) {
|
||||
return fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...this._authHeaders(),
|
||||
},
|
||||
body: JSON.stringify(content),
|
||||
}).then(this._handleResponse);
|
||||
}
|
||||
}
|
||||
|
||||
export default DjangoApi;
|
||||
export default DjangoApi;
|
||||
|
||||
Reference in New Issue
Block a user