Files
sundynix-pets/pets-fe/utils/api.js
T

63 lines
1.7 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,
header: token && auth ? { Authorization: "Bearer " + token } : {},
success(res) {
if (res.data && res.data.code === 0) resolve(res.data.data);
else {
if (res.statusCode === 401) {
wx.removeStorageSync("pet_token");
getApp().globalData.token = "";
}
const error = new Error((res.data && res.data.message) || "请求失败");
error.status = res.statusCode;
reject(error);
}
},
fail: reject,
});
});
}
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 upload(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 reject(new Error(body.message));
} catch (e) {
reject(e);
}
},
fail: reject,
});
});
}
module.exports = { request, secure, toast, upload };