// api/request.ts import { requestInterceptor } from './interceptors/request'; import { responseInterceptor } from './interceptors/response'; import type { IRequestOptions, ICreateClientConfig } from './types'; import { REQUEST_TIMEOUT } from './config'; export function createRequestClient(cfg: ICreateClientConfig) { const baseURL = cfg.baseURL; const timeout = cfg.timeout ?? REQUEST_TIMEOUT; async function request(options: IRequestOptions): Promise { // 组装 final options const final: UniApp.RequestOptions = { ...options, url: (options.url || '').startsWith('http') ? options.url : `${baseURL}${options.url}`, timeout, header: options.header || {}, }; // run request interceptor to mutate headers, etc. const intercepted = requestInterceptor(final as IRequestOptions); return new Promise((resolve, reject) => { uni.request({ ...intercepted, success(res: any) { // delegate to response interceptor responseInterceptor(res) .then((r) => { resolve(r as any); }) .catch((err) => { reject(err); }); }, fail(err: any) { uni.showToast({ title: '网络连接失败', icon: 'none' }); reject(err); }, } as any); }); } return { request }; }