35 lines
1.0 KiB
JavaScript
35 lines
1.0 KiB
JavaScript
App({
|
|
globalData: { token: "", user: null },
|
|
onLaunch() {
|
|
this.globalData.token = wx.getStorageSync("pet_token") || "";
|
|
},
|
|
async login() {
|
|
if (this.globalData.token) return this.globalData.token;
|
|
if (!this.loginPromise)
|
|
this.loginPromise = (async () => {
|
|
const { isSimulator } = require("./utils/config");
|
|
const { request } = require("./utils/api");
|
|
let data;
|
|
try {
|
|
const { code } = await wx.login();
|
|
data = await request("/auth/login", "POST", { code }, false);
|
|
} catch (error) {
|
|
if (!isSimulator) throw error;
|
|
data = await request(
|
|
"/auth/dev",
|
|
"POST",
|
|
{ key: "wechat-devtools", nickname: "本地铲屎官" },
|
|
false,
|
|
);
|
|
}
|
|
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;
|
|
},
|
|
});
|