68 lines
2.6 KiB
JavaScript
68 lines
2.6 KiB
JavaScript
window.useApi = function useApi() {
|
|
async function request(url, options = {}, extra = {}) {
|
|
const { silent = false, skipAuthRedirect = false } = extra;
|
|
try {
|
|
const mergedHeaders = {
|
|
'Content-Type': 'application/json',
|
|
...(options.headers || {}),
|
|
};
|
|
const res = await fetch(url, {
|
|
credentials: 'same-origin',
|
|
...options,
|
|
headers: mergedHeaders,
|
|
});
|
|
|
|
let json = null;
|
|
try {
|
|
json = await res.json();
|
|
} catch (e) {
|
|
if (!silent) ElementPlus.ElMessage.error('服务端返回格式错误');
|
|
return null;
|
|
}
|
|
|
|
if (res.status === 401) {
|
|
if (!skipAuthRedirect) {
|
|
window.dispatchEvent(new CustomEvent('webui-auth-required'));
|
|
}
|
|
if (!silent) ElementPlus.ElMessage.error(json.error || '未登录或会话已过期');
|
|
return null;
|
|
}
|
|
|
|
if (!json.ok) {
|
|
if (!silent) ElementPlus.ElMessage.error(json.error || '请求失败');
|
|
return null;
|
|
}
|
|
return json;
|
|
} catch (e) {
|
|
if (!silent) ElementPlus.ElMessage.error('网络请求失败');
|
|
return null;
|
|
}
|
|
}
|
|
|
|
return {
|
|
getAuthStatus: () => request('/api/auth/status', {}, { silent: true, skipAuthRedirect: true }),
|
|
login: (username, password) => request('/api/auth/login', {
|
|
method: 'POST', body: JSON.stringify({ username, password })
|
|
}, { skipAuthRedirect: true }),
|
|
logout: () => request('/api/auth/logout', { method: 'POST' }, { silent: true }),
|
|
changeCredentials: (payload) => request('/api/auth/change-credentials', {
|
|
method: 'POST', body: JSON.stringify(payload)
|
|
}),
|
|
|
|
getConfig: () => request('/api/config'),
|
|
saveConfig: (data) => request('/api/config', {
|
|
method: 'POST', body: JSON.stringify({ data })
|
|
}),
|
|
getPlugins: () => request('/api/plugins'),
|
|
togglePlugin: (name, enable) => request('/api/plugins/toggle', {
|
|
method: 'POST', body: JSON.stringify({ name, enable })
|
|
}),
|
|
getPluginConfig: (name) =>
|
|
request(`/api/plugins/${encodeURIComponent(name)}/config`),
|
|
savePluginConfig: (name, data) =>
|
|
request(`/api/plugins/${encodeURIComponent(name)}/config`, {
|
|
method: 'POST', body: JSON.stringify({ data })
|
|
}),
|
|
};
|
|
};
|