feat: 增加环境切换
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { getApiConfig } from '../config/api';
|
||||
import { getApiConfig, isCurrentApiConfig } from '../config/api';
|
||||
|
||||
export class ApiRequestError extends Error {
|
||||
constructor(
|
||||
@@ -28,7 +28,15 @@ export function requestApi<T>(
|
||||
if (!path.startsWith('/') || path.startsWith('//'))
|
||||
throw new Error('接口路径不正确');
|
||||
return new Promise((resolve, reject) => {
|
||||
// 公开请求、上传和登录共用检查,旧环境的响应不进入上层业务回调。
|
||||
const stale = () => {
|
||||
if (isCurrentApiConfig(config)) return false;
|
||||
reject(new ApiRequestError('接口环境已变化,请重新操作'));
|
||||
return true;
|
||||
};
|
||||
if (stale()) return;
|
||||
const success = (res: { statusCode: number; data: unknown }) => {
|
||||
if (stale()) return;
|
||||
const body = res.data as {
|
||||
code?: number;
|
||||
data?: T;
|
||||
@@ -42,7 +50,7 @@ export function requestApi<T>(
|
||||
: '接口请求失败,请稍后重试',
|
||||
res.statusCode,
|
||||
typeof body?.reason === 'string' &&
|
||||
/^[A-Z_]{1,64}$/.test(body.reason)
|
||||
/^[A-Z_]{1,64}$/.test(body.reason)
|
||||
? body.reason
|
||||
: '',
|
||||
),
|
||||
@@ -60,8 +68,12 @@ export function requestApi<T>(
|
||||
);
|
||||
} else resolve(body.data as T);
|
||||
};
|
||||
const fail = () =>
|
||||
reject(new ApiRequestError('连接失败,请确认后端已启动及网络配置'));
|
||||
const fail = () => {
|
||||
if (!stale())
|
||||
reject(
|
||||
new ApiRequestError('连接失败,请确认后端已启动及网络配置'),
|
||||
);
|
||||
};
|
||||
if (options.upload) {
|
||||
// wx.uploadFile 由运行时生成 multipart boundary,不能自行设置 JSON Content-Type。
|
||||
wx.uploadFile({
|
||||
|
||||
Reference in New Issue
Block a user