56 lines
1.7 KiB
JavaScript
56 lines
1.7 KiB
JavaScript
const API = {
|
|
baseUrl: '/api/v1',
|
|
|
|
async request(endpoint, options = {}) {
|
|
const url = `${this.baseUrl}${endpoint}`;
|
|
const token = localStorage.getItem('access_token');
|
|
|
|
const headers = {
|
|
'Accept': 'application/json',
|
|
...(options.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),
|
|
...(token ? { 'Authorization': `Bearer ${token}` } : {}),
|
|
...options.headers
|
|
};
|
|
|
|
const response = await fetch(url, { ...options, headers });
|
|
|
|
if (response.status === 401 && !options._retry) {
|
|
// Attempt token refresh
|
|
const refreshed = await this.refresh();
|
|
if (refreshed) {
|
|
return this.request(endpoint, { ...options, _retry: true });
|
|
}
|
|
}
|
|
|
|
const data = await response.json();
|
|
if (!response.ok) {
|
|
throw new Error(data.message || 'حدث خطأ ما');
|
|
}
|
|
return data;
|
|
},
|
|
|
|
async login(email, password) {
|
|
const data = await this.request('/auth/login', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ email, password })
|
|
});
|
|
localStorage.setItem('access_token', data.data.access_token);
|
|
return data;
|
|
},
|
|
|
|
async refresh() {
|
|
try {
|
|
const data = await fetch(`${this.baseUrl}/auth/refresh`, { method: 'POST' });
|
|
if (data.ok) {
|
|
const result = await data.json();
|
|
localStorage.setItem('access_token', result.data.access_token);
|
|
return true;
|
|
}
|
|
} catch (e) {
|
|
console.error('Refresh failed', e);
|
|
}
|
|
localStorage.removeItem('access_token');
|
|
return false;
|
|
}
|
|
};
|