Files
ev-charger-as/frontend/static/js/api.js.bak
2026-04-18 06:18:58 +09:00

43 lines
1.6 KiB
JavaScript

const API = (() => {
const BASE = '/api';
function token() { return localStorage.getItem('ev_token') || ''; }
async function req(method, path, body = null, isForm = false) {
const headers = {};
if (token()) headers['Authorization'] = 'Bearer ' + token();
let fetchBody = null;
if (body) {
if (isForm) {
fetchBody = body; // FormData
} else {
headers['Content-Type'] = 'application/json';
fetchBody = JSON.stringify(body);
}
}
const res = await fetch(BASE + path, { method, headers, body: fetchBody });
if (res.status === 401) { Auth.logout(); return; }
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: '오류가 발생했습니다.' }));
throw new Error(err.detail || '오류');
}
const ct = res.headers.get('content-type') || '';
if (ct.includes('spreadsheet') || ct.includes('octet')) return res.blob();
return res.json().catch(() => ({}));
}
return {
get: (path) => req('GET', path),
post: (path, body) => req('POST', path, body, body instanceof FormData),
put: (path, body) => req('PUT', path, body, body instanceof FormData),
patch: (path, body) => req('PATCH', path, body, body instanceof FormData),
delete: (path) => req('DELETE', path),
download: async (path, filename) => {
const blob = await req('GET', path);
const url = URL.createObjectURL(blob);
const a = document.createElement('a'); a.href = url; a.download = filename;
a.click(); URL.revokeObjectURL(url);
}
};
})();