feat: 增加环境切换

This commit is contained in:
R524809
2026-10-19 17:49:19 +08:00
parent 997042789d
commit fe1074e3f0
21 changed files with 968 additions and 123 deletions
@@ -0,0 +1,46 @@
import {
getApiEnvironment,
selectApiEnvironment,
type ApiEnvironment,
} from '../config/api';
import { hasPendingApiWrites } from './api-activity';
import { invalidatePendingAuthentication } from './auth-session';
let switching = false;
/** 统一切换入口:写入中不切换,保留分环境会话,重建全部页面以丢弃旧业务状态。 */
export async function switchApiEnvironment(environment: ApiEnvironment) {
if (wx.getAccountInfoSync().miniProgram.envVersion !== 'develop')
throw new Error('仅开发版可切换环境');
if (switching) throw new Error('正在切换环境,请稍候');
if (getApiEnvironment() === environment) return false;
const busyPage = getCurrentPages().some(
(page) => page.data.debugPublishLoading || page.data.isSavingProfile,
);
if (hasPendingApiWrites() || busyPage)
throw new Error('请等待当前保存或上传完成后再切换');
switching = true;
try {
selectApiEnvironment(environment);
invalidatePendingAuthentication();
const app = getApp<IAppOption>();
app.resetApiState();
// reLaunch 只重建页面,不重新执行 App.onLaunch;目标数据需要主动初始化。
try {
await new Promise<void>((resolve, reject) =>
wx.reLaunch({
url: '/pages/home/home',
success: () => resolve(),
fail: () => reject(new Error('环境已切换,请重新进入首页')),
}),
);
} finally {
app.warmAuthentication();
if (!(await app.loadPageConfig(true)))
throw new Error('已切换,目标接口连接失败');
}
return true;
} finally {
switching = false;
}
}