35 lines
1.2 KiB
JavaScript
35 lines
1.2 KiB
JavaScript
App({
|
|
globalData: { token: "", user: null },
|
|
onLaunch() {
|
|
this.globalData.token = wx.getStorageSync("pet_token") || "";
|
|
// Start immediately; pages await the same promise and display failures themselves.
|
|
this.login().catch(() => {});
|
|
},
|
|
async login() {
|
|
if (this.loginPromise) return this.loginPromise;
|
|
if (this.globalData.token) return this.globalData.token;
|
|
this.loginPromise = (async () => {
|
|
const { request } = require("./utils/api");
|
|
const { code } = await new Promise((resolve, reject) =>
|
|
wx.login({
|
|
timeout: 10000,
|
|
success: resolve,
|
|
fail: () => reject(new Error("暂时无法连接微信,请重新连接")),
|
|
}),
|
|
);
|
|
if (!code) throw new Error("微信登录未取得凭证,请重新连接");
|
|
const data = await request("/auth/login", "POST", { code }, false);
|
|
if (!data || typeof data.token !== "string" || !data.token) {
|
|
throw new Error("登录未完成,请重新连接");
|
|
}
|
|
this.globalData.token = data.token;
|
|
this.globalData.user = data.user;
|
|
wx.setStorageSync("pet_token", data.token);
|
|
return data.token;
|
|
})().finally(() => {
|
|
this.loginPromise = null;
|
|
});
|
|
return this.loginPromise;
|
|
},
|
|
});
|