Files
smeta-web/static/admin2/api.js
T

19 lines
796 B
JavaScript

export class ApiError extends Error {
constructor(status, message) { super(message); this.status = status; }
}
export async function api(path, opts = {}) {
const token = localStorage.getItem('token') || '';
const headers = {...(opts.headers || {})};
if (token) headers.Authorization = 'Bearer ' + token;
if (opts.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
const r = await fetch(path, {...opts, headers});
if (r.status === 401 || r.status === 403) throw new ApiError(r.status, 'Нужен вход оператора');
if (!r.ok) {
let detail = '';
try { detail = String((await r.json()).detail || ''); } catch (e) { /* не JSON */ }
throw new ApiError(r.status, detail || ('Ошибка ' + r.status));
}
return r.json();
}