You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/admin-instance-transport.js

96 lines
3.5 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

function mutationId() {
return globalThis.crypto?.randomUUID?.()
|| `admin-${Date.now()}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
}
function messageFromPayload(payload, status) {
const detail = Array.isArray(payload?.detail)
? payload.detail.map(item => item?.msg || '输入错误').join(';')
: payload?.detail;
return typeof detail === 'string'
? detail : (payload?.message || `请求失败 (${status})`);
}
export function createAdminInstanceTransport({
taskUrl,
fetchImpl = globalThis.fetch?.bind(globalThis),
locationImpl = globalThis.location,
csrfToken = () => globalThis.ADMIN_CSRF_TOKEN || '',
timeoutMs = 30000,
} = {}) {
if (typeof taskUrl !== 'function') throw new TypeError('taskUrl is required');
if (typeof fetchImpl !== 'function') throw new TypeError('fetch is unavailable');
async function requestJson(path, controller, options = {}) {
const timeout = setTimeout(() => controller.abort('timeout'), timeoutMs);
try {
const response = await fetchImpl(path, {
headers: { Accept: 'application/json', ...(options.headers || {}) },
credentials: 'same-origin', cache: 'no-store', signal: controller.signal,
...options,
});
if (response.status === 401) {
throw new Error(options.method ? '登录已过期,请重新登录。' : '登录已过期,请重新登录后刷新。');
}
let payload;
try { payload = await response.json(); }
catch { throw new Error('服务返回异常,请检查服务器日志后重试。'); }
if (!response.ok || payload?.ret === 0) {
const error = new Error(messageFromPayload(payload, response.status));
error.status = response.status;
throw error;
}
return { payload, response };
} finally {
clearTimeout(timeout);
}
}
async function read(path, controller) {
try {
const { payload } = await requestJson(path, controller);
return payload;
} catch (error) {
if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后重试。');
throw error;
}
}
async function mutate(path, body, controller, method = 'PATCH') {
if (locationImpl?.protocol !== 'https:'
&& !['localhost', '127.0.0.1', '[::1]'].includes(locationImpl?.hostname)) {
throw new Error('请通过 HTTPS 修改实例配置。');
}
try {
const { payload, response } = await requestJson(path, controller, {
method,
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken(),
'Idempotency-Key': mutationId(),
},
body: JSON.stringify(body),
});
if (response.status !== 202 || !taskUrl(payload)) {
const error = new Error('请求已送达,但任务回执协议无效。请勿重复提交,并联系管理员核查。');
error.status = response.status;
error.mutationMayHaveApplied = true;
throw error;
}
return payload;
} catch (error) {
if (controller.signal.reason === 'timeout') {
const timeoutError = new Error('请求超时,结果无法确认。请勿重复提交,并联系管理员核查。');
timeoutError.mutationMayHaveApplied = true;
throw timeoutError;
}
if (error?.status >= 500 || (!error?.status && error?.name !== 'AbortError')) {
error.mutationMayHaveApplied = true;
}
throw error;
}
}
return Object.freeze({ read, mutate });
}