阶段七:完成 React Feature 化与前置重构收口
This commit is contained in:
1 parent
375e84d663
commit
1a228dc35c
305 files changed
+14179
-5431
No files matched your search
@@ -0,0 +1,289 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { del, get, post, postForm, put } from './client';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals() /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
describe('request helpers', () => {
|
||||
test('encodes query parameters and includes credentials', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/items', { page: 2, keyword: 'a b', ignored: undefined })).resolves.toEqual({ ok: true });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/items?page=2&keyword=a+b', expect.objectContaining({
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
}));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('serializes JSON bodies', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await post('/login', { username: 'admin' });
|
||||
expect(fetchMock).toHaveBeenCalledWith('/login', expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username: 'admin' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('支持 PUT 和 DELETE 请求及查询参数', async () => {
|
||||
// fetchMock 是 PUT/DELETE 请求的网络替身。
|
||||
const fetchMock = vi.fn().mockImplementation(/* responseFactory 为每次调用生成独立响应体。 */ () => Promise.resolve(new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(put('/items/1', { enabled: true })).resolves.toEqual({ ok: true });
|
||||
await expect(del('/items/1', { force: true })).resolves.toEqual({ ok: true });
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/items/1', expect.objectContaining({ method: 'PUT', body: JSON.stringify({ enabled: true }) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/items/1?force=true', expect.objectContaining({ method: 'DELETE' }));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('surfaces unified backend errors', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ code: 'bad_request', message: 'bad request' }), {
|
||||
status: 400,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
await expect(get('/bad')).rejects.toThrow('bad request');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('使用非 JSON 错误文本作为失败消息', async () => {
|
||||
// fetchMock 是返回纯文本错误的网络替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('网关暂时不可用', {
|
||||
status: 502,
|
||||
headers: { 'content-type': 'text/plain' },
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/gateway')).rejects.toThrow('网关暂时不可用');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('成功的非 JSON 响应直接返回文本', async () => {
|
||||
// fetchMock 是返回纯文本成功响应的网络替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('ok', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'text/plain' },
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/text')).resolves.toBe('ok');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('JSON 错误体无法解析时使用 HTTP 状态兜底', async () => {
|
||||
// fetchMock 是返回损坏 JSON 错误体的网络替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('{broken', {
|
||||
status: 500,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/broken')).rejects.toThrow('请求失败: 500');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('普通请求纯文本错误体读取失败时使用状态码兜底', /* 当前回调验证普通请求文本错误读取失败分支。 */ async () => {
|
||||
// response 是文本读取失败的普通请求响应替身。
|
||||
const response = { ok: false, status: 502, headers: { get: /* contentTypeGetter 返回纯文本类型。 */ () => 'text/plain' }, text: vi.fn().mockRejectedValue(new Error('读取失败')) } as unknown as Response;
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
|
||||
await expect(get('/broken-text')).rejects.toThrow('请求失败: 502');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('网络层异常原样透传', async () => {
|
||||
// fetchMock 是抛出非取消网络异常的替身。
|
||||
const fetchMock = vi.fn().mockRejectedValue(new Error('网络断开'));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(get('/network-error')).rejects.toThrow('网络断开');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('notifies the app when an authenticated request returns 401', async () => {
|
||||
const events = new EventTarget(); /* events 表示events。 */
|
||||
const listener = vi.fn(); /* listener 表示listener。 */
|
||||
events.addEventListener('auth:logout', listener);
|
||||
vi.stubGlobal('window', events);
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', {
|
||||
status: 401,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
|
||||
await expect(get('/private')).rejects.toThrow();
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('并发认证失败只触发一次登出事件', /* 当前回调验证认证失效通知的并发去重。 */ async () => {
|
||||
// events 是认证失效事件分发目标。
|
||||
const events = new EventTarget();
|
||||
// listener 是认证失效事件监听器。
|
||||
const listener = vi.fn();
|
||||
events.addEventListener('auth:logout', listener);
|
||||
vi.stubGlobal('window', events);
|
||||
vi.stubGlobal('fetch', vi.fn().mockImplementation(/* responseFactory 为每次调用生成认证失败响应。 */ () => Promise.resolve(new Response('{}', {
|
||||
status: 401,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}))));
|
||||
|
||||
await Promise.allSettled([get('/private-a'), get('/private-b')]);
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('does not notify logout for a failed login request', async () => {
|
||||
const events = new EventTarget(); /* events 表示events。 */
|
||||
const listener = vi.fn(); /* listener 表示listener。 */
|
||||
events.addEventListener('auth:logout', listener);
|
||||
vi.stubGlobal('window', events);
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', {
|
||||
status: 401,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
|
||||
await expect(post('/login', {}, { skipAuthLogout: true })).rejects.toThrow();
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('posts FormData without forcing a content type', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('ok', { status: 200 })); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const form = new FormData(); /* form 表示form。 */
|
||||
form.set('name', 'value');
|
||||
await expect(postForm('/upload', form)).resolves.toBe('ok');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/upload', expect.objectContaining({
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: form,
|
||||
}));
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('aborts requests at the configured timeout', async () => {
|
||||
vi.useFakeTimers();
|
||||
const fetchMock = vi.fn((_url: string, init: RequestInit) => new Promise<Response>((_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')) /* 回调函数负责当前业务流程。 */, { once: true });
|
||||
} /* 回调函数负责当前业务流程。 */) /* 回调函数负责当前业务流程。 */); /* fetchMock 表示fetchMock。 */
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const pending = get('/slow', undefined, { timeoutMs: 50 }); /* pending 表示pending。 */
|
||||
const rejection = expect(pending).rejects.toThrow('请求超时'); /* rejection 表示rejection。 */
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
await rejection;
|
||||
vi.useRealTimers();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('上传请求超时后返回上传专用错误', /* 当前回调验证上传请求的超时错误分支。 */ async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
// fetchMock 是等待上传超时信号的网络替身。
|
||||
const fetchMock = vi.fn(/* uploadTimeoutFactory 创建等待上传超时的网络替身。 */ (_url: string, init: RequestInit) => new Promise<Response>(/* uploadTimeoutExecutor 等待上传控制器超时。 */ (_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', /* abortCallback 将上传超时转换为网络异常。 */ () => reject(new DOMException('timeout', 'AbortError')), { once: true });
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
// pending 是等待上传超时结果的请求 Promise。
|
||||
const pending = postForm('/slow-upload', new FormData(), { timeoutMs: 50 });
|
||||
// rejection 是断言上传超时错误的异步结果。
|
||||
const rejection = expect(pending).rejects.toThrow('上传超时');
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
await rejection;
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('外部 AbortSignal 取消请求时返回取消错误', async () => {
|
||||
// controller 是调用方主动取消请求的控制器。
|
||||
const controller = new AbortController();
|
||||
// fetchMock 是等待外部取消信号的网络替身。
|
||||
const fetchMock = vi.fn((_url: string, init: RequestInit) => new Promise<Response>(
|
||||
/* fetchPromiseExecutor 等待请求信号触发取消。 */ (_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', /* abortCallback 将取消转换为网络异常。 */ () => reject(new DOMException('aborted', 'AbortError')), { once: true });
|
||||
},
|
||||
));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
// pending 是等待外部取消结果的请求 Promise。
|
||||
const pending = get('/cancelled', undefined, { signal: controller.signal });
|
||||
controller.abort();
|
||||
await expect(pending).rejects.toThrow('请求已取消');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('上传请求支持外部取消并返回取消错误', async () => {
|
||||
// controller 是上传调用方主动取消请求的控制器。
|
||||
const controller = new AbortController();
|
||||
// fetchMock 是等待上传取消信号的网络替身。
|
||||
const fetchMock = vi.fn((_url: string, init: RequestInit) => new Promise<Response>(
|
||||
/* uploadPromiseExecutor 等待上传信号触发取消。 */ (_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', /* abortCallback 将上传取消转换为网络异常。 */ () => reject(new DOMException('aborted', 'AbortError')), { once: true });
|
||||
},
|
||||
));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
// pending 是等待上传取消结果的请求 Promise。
|
||||
const pending = postForm('/upload', new FormData(), { signal: controller.signal });
|
||||
controller.abort();
|
||||
await expect(pending).rejects.toThrow('请求已取消');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('上传网络层异常原样透传', async () => {
|
||||
// fetchMock 是抛出非取消上传异常的替身。
|
||||
const fetchMock = vi.fn().mockRejectedValue(new Error('上传网络断开'));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(postForm('/upload', new FormData())).rejects.toThrow('上传网络断开');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('上传失败保留原始错误载荷', async () => {
|
||||
// payload 是服务端返回的上传错误详情。
|
||||
const payload = { code: 'invalid_file', message: '文件格式不支持' };
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify(payload), {
|
||||
status: 422,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
|
||||
try {
|
||||
await postForm('/upload', new FormData());
|
||||
throw new Error('应当抛出上传错误');
|
||||
} catch (error /* error 表示上传异常。 */) {
|
||||
// uploadError 是包含后端载荷的上传异常。
|
||||
const uploadError = error as Error & { /* payload 表示原始错误载荷。 */ payload?: unknown };
|
||||
expect(uploadError.message).toBe('文件格式不支持');
|
||||
expect(uploadError.payload).toEqual(payload);
|
||||
}
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('非 JSON 上传错误体读取失败时使用状态码兜底', /* 当前回调验证上传错误文本读取失败分支。 */ async () => {
|
||||
// response 是文本读取失败的上传响应替身。
|
||||
const response = { ok: false, status: 500, headers: { get: /* contentTypeGetter 返回纯文本类型。 */ () => 'text/plain' }, text: vi.fn().mockRejectedValue(new Error('读取失败')) } as unknown as Response;
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
|
||||
await expect(postForm('/upload', new FormData())).rejects.toThrow('请求失败: 500');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('上传认证失败也会触发登出事件', /* 当前回调验证上传请求的认证失效通知。 */ async () => {
|
||||
// events 是上传认证失效事件分发目标。
|
||||
const events = new EventTarget();
|
||||
// listener 是上传认证失效事件监听器。
|
||||
const listener = vi.fn();
|
||||
events.addEventListener('auth:logout', listener);
|
||||
vi.stubGlobal('window', events);
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', {
|
||||
status: 401,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
await expect(postForm('/upload', new FormData())).rejects.toThrow();
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('请求开始前已取消的外部信号返回取消错误', /* 当前回调验证预取消信号分支。 */ async () => {
|
||||
// controller 是预先取消请求的外部控制器。
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
// fetchMock 是观察预取消信号的网络替身。
|
||||
const fetchMock = vi.fn(/* fetchFactory 创建预取消信号网络替身。 */ (_url: string, init: RequestInit) => new Promise<Response>(/* fetchExecutor 观察预取消信号。 */ (_resolve, reject) => {
|
||||
if (init.signal?.aborted) reject(new DOMException('aborted', 'AbortError'));
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(get('/pre-cancelled', undefined, { signal: controller.signal })).rejects.toThrow('请求已取消');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
@@ -0,0 +1,161 @@
|
||||
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
|
||||
type QueryParams = Record<string, string | number | boolean | undefined | null>;
|
||||
|
||||
type JsonValue = unknown;
|
||||
|
||||
export type RequestControlOptions = {
|
||||
// signal 表示signal。
|
||||
signal?: AbortSignal;
|
||||
// timeoutMs 表示timeoutMs。
|
||||
timeoutMs?: number;
|
||||
};
|
||||
|
||||
type RequestOptions = {
|
||||
// params 表示params。
|
||||
params?: QueryParams;
|
||||
// body 表示请求体。
|
||||
body?: JsonValue;
|
||||
// skipAuthLogout 表示skipAuthLogout。
|
||||
skipAuthLogout?: boolean;
|
||||
} & RequestControlOptions;
|
||||
|
||||
const defaultRequestTimeoutMs = 30_000; /* defaultRequestTimeoutMs 表示default接口请求对象TimeoutMs。 */
|
||||
const uploadRequestTimeoutMs = 10 * 60_000; /* uploadRequestTimeoutMs 表示upload接口请求对象TimeoutMs。 */
|
||||
|
||||
let authLogoutPending = false; /* authLogoutPending 表示authLogoutPending。 */
|
||||
|
||||
const notifyAuthExpired = () => {
|
||||
if (authLogoutPending || typeof window === 'undefined') return;
|
||||
authLogoutPending = true;
|
||||
window.dispatchEvent(new Event('auth:logout'));
|
||||
queueMicrotask(() => {
|
||||
authLogoutPending = false;
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
}; /* notifyAuthExpired 表示notifyAuthExpired。 */
|
||||
|
||||
const buildQueryString = (params?: QueryParams): string => {
|
||||
if (!params) return '';
|
||||
const searchParams = new URLSearchParams(); /* searchParams 表示searchParams。 */
|
||||
for (const [key, rawVal] /* [key, rawVal] 表示keyrawVal。 */ of Object.entries(params)) {
|
||||
if (rawVal === undefined || rawVal === null) continue;
|
||||
searchParams.set(key, String(rawVal));
|
||||
}
|
||||
const qs = searchParams.toString(); /* qs 表示qs。 */
|
||||
return qs ? `?${qs}` : '';
|
||||
}; /* buildQueryString 表示buildQueryString。 */
|
||||
|
||||
const request = async <T>(method: RequestMethod, url: string, options: RequestOptions = {}): Promise<T> => {
|
||||
const qs = buildQueryString(options.params); /* qs 表示qs。 */
|
||||
const fullUrl = `${url}${qs}`; /* fullUrl 表示full请求地址。 */
|
||||
|
||||
const control = controlledSignal(options.signal, options.timeoutMs ?? defaultRequestTimeoutMs); /* control 表示control。 */
|
||||
let res: Response; /* res 表示接口响应结果。 */
|
||||
try {
|
||||
res = await fetch(fullUrl, {
|
||||
method,
|
||||
credentials: 'include',
|
||||
signal: control.signal,
|
||||
headers: {
|
||||
...(options.body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
});
|
||||
} catch (error /* error 表示当前操作返回的错误。 */) {
|
||||
if (control.signal.aborted) {
|
||||
throw new Error(options.signal?.aborted ? '请求已取消' : '请求超时,请稍后重试');
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
control.cleanup();
|
||||
}
|
||||
|
||||
const contentType = res.headers.get('content-type') || ''; /* contentType 表示contentType。 */
|
||||
const isJson = contentType.includes('application/json'); /* isJson 表示isJson。 */
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 && !options.skipAuthLogout) notifyAuthExpired();
|
||||
// payload 是后端统一错误 DTO 或非 JSON 错误文本。
|
||||
const payload = isJson ? await res.json().catch(() => undefined /* 回调函数负责当前业务流程。 */) : await res.text().catch(() => undefined /* 回调函数负责当前业务流程。 */);
|
||||
const message = errorMessageFromPayload(payload, res.status); // message 是统一错误 DTO 提取出的用户可见说明。
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
if (!isJson) {
|
||||
// 这里按现有后端习惯基本都会返回JSON;非JSON时直接返回text
|
||||
return (await res.text()) as unknown as T;
|
||||
}
|
||||
|
||||
return (await res.json()) as T;
|
||||
}; /* request 表示接口请求对象。 */
|
||||
|
||||
export const get = async <T>(url: string, params?: QueryParams, options?: RequestControlOptions): Promise<T> => request<T>('GET', url, { params, ...options }); /* get 表示get。 */
|
||||
export const post = async <T>(url: string, body?: JsonValue, options?: RequestControlOptions & { /* skipAuthLogout 表示skipAuthLogout。 */ skipAuthLogout?: boolean }): Promise<T> => request<T>('POST', url, { body, ...options }); /* post 表示post。 */
|
||||
export const put = async <T>(url: string, body?: JsonValue, options?: RequestControlOptions): Promise<T> => request<T>('PUT', url, { body, ...options }); /* put 表示put。 */
|
||||
export const del = async <T>(url: string, params?: QueryParams, options?: RequestControlOptions): Promise<T> => request<T>('DELETE', url, { params, ...options }); /* del 表示del。 */
|
||||
|
||||
export const postForm = async <T>(url: string, body: FormData, options: RequestControlOptions = {}): Promise<T> => {
|
||||
const control = controlledSignal(options.signal, options.timeoutMs ?? uploadRequestTimeoutMs); /* control 表示control。 */
|
||||
let res: Response; /* res 表示接口响应结果。 */
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
signal: control.signal,
|
||||
body,
|
||||
});
|
||||
} catch (error /* error 表示当前操作返回的错误。 */) {
|
||||
if (control.signal.aborted) {
|
||||
throw new Error(options.signal?.aborted ? '请求已取消' : '上传超时,请稍后重试');
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
control.cleanup();
|
||||
}
|
||||
|
||||
const contentType = res.headers.get('content-type') || ''; /* contentType 表示contentType。 */
|
||||
const isJson = contentType.includes('application/json'); /* isJson 表示isJson。 */
|
||||
const payload = isJson ? await res.json().catch(() => undefined /* 回调函数负责当前业务流程。 */) : await res.text().catch(() => undefined /* 回调函数负责当前业务流程。 */); /* payload 表示payload。 */
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) notifyAuthExpired();
|
||||
const message = errorMessageFromPayload(payload, res.status); // message 是上传失败时统一错误 DTO 提取出的说明。
|
||||
const err = new Error(message) as Error & { /* payload 表示payload。 */ payload?: unknown }; /* err 表示当前操作返回的错误。 */
|
||||
err.payload = payload;
|
||||
throw err;
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
}; /* postForm 表示postForm。 */
|
||||
|
||||
const controlledSignal = (external: AbortSignal | undefined, timeoutMs: number) => {
|
||||
const controller = new AbortController(); /* controller 表示controller。 */
|
||||
const abortFromExternal = () => controller.abort(external?.reason); /* abortFromExternal 表示abortFromExternal。 */
|
||||
if (external?.aborted) abortFromExternal();
|
||||
else external?.addEventListener('abort', abortFromExternal, { once: true });
|
||||
const timer = globalThis.setTimeout(() => controller.abort(new DOMException('timeout', 'TimeoutError')) /* 回调函数负责当前业务流程。 */, Math.max(1, timeoutMs)); /* timer 表示timer。 */
|
||||
return {
|
||||
signal: controller.signal,
|
||||
cleanup: () => {
|
||||
globalThis.clearTimeout(timer);
|
||||
external?.removeEventListener('abort', abortFromExternal);
|
||||
} /* 回调函数负责当前业务流程。 */,
|
||||
};
|
||||
}; /* controlledSignal 表示controlledSignal。 */
|
||||
|
||||
/** 判断响应体是否符合统一 HTTP 错误 DTO。 */
|
||||
const isApiErrorResponse = (payload: unknown): payload is ApiErrorResponse => {
|
||||
if (typeof payload !== 'object' || payload === null) return false;
|
||||
// candidate 是待校验的未知 JSON 对象视图。
|
||||
const candidate = payload as Record<string, unknown>;
|
||||
return typeof candidate.code === 'string' && typeof candidate.message === 'string';
|
||||
};
|
||||
|
||||
/** 从统一错误 DTO 提取用户可见消息,拒绝继续依赖 detail 或 msg 别名。 */
|
||||
const errorMessageFromPayload = (payload: unknown, status: number): string => {
|
||||
if (typeof payload === 'string') return payload;
|
||||
if (isApiErrorResponse(payload)) return payload.message;
|
||||
return `请求失败: ${status}`;
|
||||
};
|
||||
|
||||
import type { ApiErrorResponse } from '../api-contract';
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { collectionFrom, objectFrom } from './contract';
|
||||
|
||||
/** ContractRow 是集合归一测试使用的最小具名行模型。 */
|
||||
interface ContractRow {
|
||||
/** id 是测试集合项的稳定标识。 */
|
||||
id: number;
|
||||
}
|
||||
|
||||
describe('HTTP transport contract normalizers', () => {
|
||||
test('集合归一器接受数组、null、命名包裹和双层 data 包裹', /* 回调验证集合响应的兼容归一规则。 */ () => {
|
||||
// rows 是不同发布版本可能返回的集合响应形状。
|
||||
const rows = [{
|
||||
// id 是测试集合项的稳定标识。
|
||||
id: 1,
|
||||
}];
|
||||
expect(collectionFrom<ContractRow>(rows)).toEqual(rows);
|
||||
expect(collectionFrom<ContractRow>(null)).toEqual([]);
|
||||
expect(collectionFrom<ContractRow>({ items: rows }, ['items'])).toEqual(rows);
|
||||
expect(collectionFrom<ContractRow>({ data: { results: rows } }, ['results'])).toEqual(rows);
|
||||
});
|
||||
|
||||
test('对象归一器保留直接对象并展开 data/result 历史包裹', /* 回调验证对象响应的兼容归一规则。 */ () => {
|
||||
// direct 是当前版本直接返回的对象契约。
|
||||
const direct = { /** enabled 表示测试对象的启用状态。 */ enabled: true };
|
||||
expect(objectFrom<typeof direct>(direct)).toEqual(direct);
|
||||
expect(objectFrom<typeof direct>({ data: direct })).toEqual(direct);
|
||||
expect(objectFrom<typeof direct>({ result: direct })).toEqual(direct);
|
||||
expect(objectFrom<typeof direct>(null)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
/** HTTP transport 响应的兼容归一工具;这里只处理 JSON 形状,不承载任何业务规则。 */
|
||||
|
||||
/** JSON 对象的最小运行时视图,避免业务 API 适配器依赖 any。 */
|
||||
export type JsonObject = Record<string, unknown>;
|
||||
|
||||
/** 判断未知值是否可以作为 JSON 对象读取。 */
|
||||
export const isJsonObject = (value: unknown): value is JsonObject =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
|
||||
/**
|
||||
* 从数组、空值或历史包裹对象中提取集合。
|
||||
* 空值、缺失字段和非数组字段统一返回新建空数组,避免页面把 null 当作可迭代值。
|
||||
*/
|
||||
export const collectionFrom = <T>(payload: unknown, keys: readonly string[] = ['data', 'items', 'results']): T[] => {
|
||||
// currentPayload 保存当前待检查的响应层,允许兼容 data 嵌套对象但不跨越无关字段。
|
||||
let currentPayload: unknown = payload;
|
||||
// depth 防止异常响应对象造成无限递归;服务端契约最多允许两层历史包裹。
|
||||
let depth = 0;
|
||||
for (; depth < 2; depth += 1) {
|
||||
if (Array.isArray(currentPayload)) return currentPayload as T[];
|
||||
if (!isJsonObject(currentPayload)) return [];
|
||||
// key 表示当前兼容契约允许的集合字段名。
|
||||
for (const key /* key 是当前允许读取的集合字段名。 */ of keys) {
|
||||
// candidate 表示候选集合字段;null 视为服务端空集合。
|
||||
const candidate = currentPayload[key];
|
||||
if (Array.isArray(candidate)) return candidate as T[];
|
||||
if (candidate === null) return [];
|
||||
}
|
||||
// nestedPayload 兼容 { data: { items: [...] } } 这一历史包裹形状。
|
||||
const nestedPayload = currentPayload.data;
|
||||
if (isJsonObject(nestedPayload)) {
|
||||
currentPayload = nestedPayload;
|
||||
continue;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 从直接对象或 data/result 包裹对象中提取对象。
|
||||
* 非对象和 null 都返回 undefined,由 feature 适配器决定默认值。
|
||||
*/
|
||||
export const objectFrom = <T>(payload: unknown, keys: readonly string[] = ['data', 'result']): T | undefined => {
|
||||
// currentPayload 保存当前待检查的响应层,兼容最多两层历史包裹。
|
||||
let currentPayload: unknown = payload;
|
||||
// depth 限制兼容层深度,防止错误响应触发无限遍历。
|
||||
let depth = 0;
|
||||
for (; depth < 2; depth += 1) {
|
||||
if (!isJsonObject(currentPayload)) return undefined;
|
||||
// key 表示当前兼容契约允许的对象字段名。
|
||||
for (const key /* key 是当前允许读取的对象字段名。 */ of keys) {
|
||||
// candidate 表示候选对象字段;null 表示没有可用对象。
|
||||
const candidate = currentPayload[key];
|
||||
if (isJsonObject(candidate)) return candidate as T;
|
||||
}
|
||||
return currentPayload as T;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
Reference in new issue
Block a user