84 lines
2.5 KiB
JavaScript
84 lines
2.5 KiB
JavaScript
const { baseURL } = require("./config");
|
|
function request(path, method = "GET", data, auth = true) {
|
|
return new Promise((resolve, reject) => {
|
|
const token = getApp().globalData.token || wx.getStorageSync("pet_token");
|
|
wx.request({
|
|
url: baseURL + path,
|
|
method,
|
|
data,
|
|
timeout: 15000,
|
|
header: token && auth ? { Authorization: "Bearer " + token } : {},
|
|
success(res) {
|
|
if (res.data && res.data.code === 0) resolve(res.data.data);
|
|
else {
|
|
if (res.statusCode === 401 && auth) invalidateToken(token);
|
|
const error = new Error((res.data && res.data.message) || "请求失败");
|
|
error.status = res.statusCode;
|
|
reject(error);
|
|
}
|
|
},
|
|
fail: () => reject(new Error("网络连接失败,请检查网络后重试")),
|
|
});
|
|
});
|
|
}
|
|
function invalidateToken(usedToken) {
|
|
const app = getApp();
|
|
// A late response using the old token must not clear a newly refreshed session.
|
|
if (app.globalData.token && app.globalData.token !== usedToken) return;
|
|
wx.removeStorageSync("pet_token");
|
|
app.globalData.token = "";
|
|
app.globalData.user = null;
|
|
}
|
|
async function secure(path, method, data) {
|
|
await getApp().login();
|
|
try {
|
|
return await request(path, method, data);
|
|
} catch (error) {
|
|
if (error.status === 401) {
|
|
await getApp().login();
|
|
return request(path, method, data);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
function toast(error) {
|
|
wx.showToast({ title: error.message || "操作失败", icon: "none" });
|
|
}
|
|
function uploadOnce(path) {
|
|
return new Promise((resolve, reject) => {
|
|
const token = getApp().globalData.token;
|
|
wx.uploadFile({
|
|
url: baseURL + "/files",
|
|
filePath: path,
|
|
name: "file",
|
|
header: { Authorization: "Bearer " + token },
|
|
success(res) {
|
|
try {
|
|
const body = JSON.parse(res.data);
|
|
if (body.code === 0) resolve(body.data);
|
|
else {
|
|
const error = new Error(body.message || "上传失败");
|
|
error.status = res.statusCode;
|
|
if (res.statusCode === 401) invalidateToken(token);
|
|
reject(error);
|
|
}
|
|
} catch (e) {
|
|
reject(e);
|
|
}
|
|
},
|
|
fail: reject,
|
|
});
|
|
});
|
|
}
|
|
async function upload(path) {
|
|
await getApp().login();
|
|
try {
|
|
return await uploadOnce(path);
|
|
} catch (error) {
|
|
if (error.status !== 401) throw error;
|
|
await getApp().login();
|
|
return uploadOnce(path);
|
|
}
|
|
}
|
|
module.exports = { request, secure, toast, upload };
|