8a48765a46
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
91 lines
2.7 KiB
JavaScript
91 lines
2.7 KiB
JavaScript
import { CanceledError, isCancel } from 'axios';
|
|
|
|
const PUBLIC_API_PATH =
|
|
/^\/api\/(?:status|setup|i18n|notice|about|privacy_policy|user_agreement|home_page_content|customer-service|verification|reset_password|oauth|user\/(?:login|register|reset|passkey\/login)|org\/(?:login|register))(?:\/|$)/;
|
|
const READ_METHODS = new Set(['get', 'head', 'options']);
|
|
|
|
function isSessionBound(config) {
|
|
const pathname = config?.url?.split(/[?#]/, 1)[0];
|
|
return (
|
|
config?.sessionBound !== false &&
|
|
pathname?.startsWith('/api/') &&
|
|
!PUBLIC_API_PATH.test(pathname)
|
|
);
|
|
}
|
|
|
|
function combineSignals(signals, config, cleanups) {
|
|
const inputs = [...new Set(signals.filter(Boolean))];
|
|
if (inputs.length < 2) return inputs[0];
|
|
if (typeof AbortSignal.any === 'function') return AbortSignal.any(inputs);
|
|
|
|
const controller = new AbortController();
|
|
const abort = () => controller.abort();
|
|
for (const input of inputs) {
|
|
if (input.aborted) abort();
|
|
else input.addEventListener('abort', abort, { once: true });
|
|
}
|
|
cleanups.set(config, () => {
|
|
for (const input of inputs) input.removeEventListener('abort', abort);
|
|
});
|
|
return controller.signal;
|
|
}
|
|
|
|
export function installRequestLifecycle(
|
|
instance,
|
|
{ onError, onSessionExpired },
|
|
) {
|
|
const session = new AbortController();
|
|
const cleanups = new WeakMap();
|
|
|
|
instance.interceptors.request.use((config) => {
|
|
const sessionBound = isSessionBound(config);
|
|
const read = READ_METHODS.has(config.method);
|
|
const groupSignal = read ? config.requestGroup?.signal : undefined;
|
|
if ((sessionBound && session.signal.aborted) || groupSignal?.aborted) {
|
|
throw new CanceledError(undefined, config);
|
|
}
|
|
config.signal = combineSignals(
|
|
[config.signal, read && sessionBound && session.signal, groupSignal],
|
|
config,
|
|
cleanups,
|
|
);
|
|
return config;
|
|
});
|
|
|
|
const cleanup = (config) => {
|
|
cleanups.get(config)?.();
|
|
cleanups.delete(config);
|
|
};
|
|
|
|
instance.interceptors.response.use(
|
|
(response) => {
|
|
cleanup(response.config);
|
|
return response;
|
|
},
|
|
(error) => {
|
|
const { config, response } = error;
|
|
cleanup(config);
|
|
const sessionBound = isSessionBound(config);
|
|
const read = READ_METHODS.has(config?.method);
|
|
if (isCancel(error)) throw error;
|
|
if (sessionBound && session.signal.aborted) {
|
|
if (read) throw new CanceledError(undefined, config);
|
|
throw error;
|
|
}
|
|
if (response?.status >= 400 && read) config.requestGroup?.abort();
|
|
|
|
if (!config?.skipErrorHandler) {
|
|
if (response?.status === 401 && sessionBound) {
|
|
session.abort();
|
|
onSessionExpired();
|
|
} else {
|
|
onError(error);
|
|
}
|
|
}
|
|
throw error;
|
|
},
|
|
);
|
|
|
|
return () => session.abort();
|
|
}
|