74 lines
2.0 KiB
JavaScript
74 lines
2.0 KiB
JavaScript
/**
|
|
* مُصادَق — API Client with JWT Auth & Refresh Flow
|
|
*/
|
|
window.API = {
|
|
baseUrl: '/Application/public/api.php',
|
|
accessToken: localStorage.getItem('access_token'),
|
|
|
|
async get(path) {
|
|
return this._request('GET', path);
|
|
},
|
|
|
|
async post(path, body) {
|
|
return this._request('POST', path, body);
|
|
},
|
|
|
|
async upload(path, formData) {
|
|
return this._request('POST', path, formData, true);
|
|
},
|
|
|
|
async _request(method, path, body = null, isFormData = false) {
|
|
const headers = {
|
|
'Accept': 'application/json',
|
|
};
|
|
|
|
if (this.accessToken) {
|
|
headers['Authorization'] = `Bearer ${this.accessToken}`;
|
|
}
|
|
|
|
if (!isFormData && body) {
|
|
headers['Content-Type'] = 'application/json';
|
|
body = JSON.stringify(body);
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
method,
|
|
headers,
|
|
body
|
|
});
|
|
|
|
if (response.status === 401) {
|
|
const refreshed = await this.refreshToken();
|
|
if (refreshed) {
|
|
return this._request(method, path, body, isFormData);
|
|
} else {
|
|
window.location.href = '/login';
|
|
}
|
|
}
|
|
|
|
const data = await response.json();
|
|
if (!response.ok) throw data;
|
|
return data;
|
|
} catch (error) {
|
|
console.error('API Error:', error);
|
|
throw error;
|
|
}
|
|
},
|
|
|
|
async refreshToken() {
|
|
try {
|
|
const response = await fetch(`${this.baseUrl}/auth/refresh`, { method: 'POST' });
|
|
if (response.ok) {
|
|
const result = await response.json();
|
|
this.accessToken = result.data.access_token;
|
|
localStorage.setItem('access_token', this.accessToken);
|
|
return true;
|
|
}
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
return false;
|
|
}
|
|
};
|