Update codebase
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
// api/client.js — عميل HTTP رفيع لبوابة transit/connect_admin.php
|
||||
// كل الردود بنمط {status:'success'|'failure', message: ...}
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_BASE || 'https://api.siromove.com/transit'
|
||||
const TOKEN_KEY = 'transit_admin_token'
|
||||
|
||||
export function getToken() {
|
||||
return localStorage.getItem(TOKEN_KEY) || ''
|
||||
}
|
||||
export function setToken(token) {
|
||||
if (token) localStorage.setItem(TOKEN_KEY, token)
|
||||
else localStorage.removeItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
class ApiError extends Error {
|
||||
constructor(message, status) {
|
||||
super(message)
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
async function request(path, body, { isForm = false } = {}) {
|
||||
const headers = {}
|
||||
const token = getToken()
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`
|
||||
|
||||
let payload
|
||||
if (isForm) {
|
||||
payload = body // already FormData
|
||||
} else {
|
||||
headers['Content-Type'] = 'application/x-www-form-urlencoded'
|
||||
const params = new URLSearchParams()
|
||||
Object.entries(body || {}).forEach(([k, v]) => {
|
||||
if (v !== undefined && v !== null) params.append(k, v)
|
||||
})
|
||||
payload = params
|
||||
}
|
||||
|
||||
let res
|
||||
try {
|
||||
res = await fetch(`${API_BASE}/${path}`, { method: 'POST', headers, body: payload })
|
||||
} catch (e) {
|
||||
throw new ApiError('تعذّر الاتصال بالخادم — تحقق من اتصالك بالإنترنت', 0)
|
||||
}
|
||||
|
||||
if (res.status === 401) {
|
||||
setToken(null)
|
||||
throw new ApiError('انتهت الجلسة — سجّل الدخول مجدداً', 401)
|
||||
}
|
||||
|
||||
let json
|
||||
try {
|
||||
json = await res.json()
|
||||
} catch (e) {
|
||||
throw new ApiError('استجابة غير صالحة من الخادم', res.status)
|
||||
}
|
||||
|
||||
if (json.status !== 'success') {
|
||||
const msg = typeof json.message === 'string' ? json.message : 'حدث خطأ، حاول مجدداً'
|
||||
throw new ApiError(msg, res.status)
|
||||
}
|
||||
|
||||
return json.message
|
||||
}
|
||||
|
||||
export const api = { request }
|
||||
export { ApiError }
|
||||
Reference in New Issue
Block a user