55 lines
1.7 KiB
TypeScript
55 lines
1.7 KiB
TypeScript
// api/request.ts
|
||
import { requestInterceptor } from './interceptors/request';
|
||
import { responseInterceptor } from './interceptors/response';
|
||
import type { IRequestOptions, ICreateClientConfig } from './types';
|
||
import { REQUEST_TIMEOUT } from './config';
|
||
import { t } from '@/utils/i18n'
|
||
|
||
export function createRequestClient(cfg: ICreateClientConfig) {
|
||
const baseURL = cfg.baseURL;
|
||
const timeout = cfg.timeout ?? REQUEST_TIMEOUT;
|
||
|
||
async function request<T = any>(options: IRequestOptions): Promise<T> {
|
||
// 组装 final options
|
||
const final: UniApp.RequestOptions = {
|
||
...options,
|
||
url: (options.url || '').startsWith('http') ? options.url : `${baseURL}${options.url}`,
|
||
timeout,
|
||
header: options.header || {},
|
||
};
|
||
|
||
// 运行请求拦截器,修改 headers 等
|
||
const intercepted = requestInterceptor(final as IRequestOptions);
|
||
|
||
// 全局处理请求 loading
|
||
const loading = !cfg.loading ? true : cfg.loading // 接口请求参数不传loading,默认显示loading
|
||
loading && uni.showLoading()
|
||
|
||
return new Promise((resolve, reject) => {
|
||
uni.request({
|
||
...intercepted,
|
||
complete() {
|
||
// 请求完成关闭 loading
|
||
loading && uni.hideLoading()
|
||
},
|
||
success(res: any) {
|
||
// 委托给响应拦截器处理
|
||
responseInterceptor(res)
|
||
.then((r) => {
|
||
resolve(r as any);
|
||
})
|
||
.catch((err) => {
|
||
reject(err);
|
||
});
|
||
},
|
||
fail(err: any) {
|
||
uni.showToast({ title: t('global.networkConnectionError'), icon: 'none' });
|
||
reject(err);
|
||
},
|
||
} as any);
|
||
});
|
||
}
|
||
|
||
return { request };
|
||
}
|