74 lines
2.1 KiB
JavaScript
74 lines
2.1 KiB
JavaScript
const { apiBase } = require("./config");
|
|
|
|
function token() {
|
|
return wx.getStorageSync("ql_token") || "";
|
|
}
|
|
|
|
/** 统一请求:成功返回 data,失败抛 {code, message, status}。 */
|
|
function request(method, path, body) {
|
|
return new Promise((resolve, reject) => {
|
|
const header = { "Content-Type": "application/json" };
|
|
const t = token();
|
|
if (t) header.Authorization = "Bearer " + t;
|
|
|
|
wx.request({
|
|
url: apiBase + path,
|
|
method,
|
|
data: body || {},
|
|
header,
|
|
timeout: 15000,
|
|
success(res) {
|
|
const data = res.data || {};
|
|
if (res.statusCode >= 200 && res.statusCode < 300 && data.ok) {
|
|
resolve(data.data);
|
|
return;
|
|
}
|
|
const err = (data && data.error) || {};
|
|
if (res.statusCode === 401) {
|
|
getApp().clearAuth();
|
|
}
|
|
reject({ code: err.code || "HTTP_" + res.statusCode, message: err.message || "请求失败", status: res.statusCode });
|
|
},
|
|
fail(e) {
|
|
reject({
|
|
code: "NETWORK",
|
|
message: "连不上后端(" + apiBase + "):" + (e.errMsg || ""),
|
|
});
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
const get = (path) => request("GET", path);
|
|
const post = (path, body) => request("POST", path, body);
|
|
const patch = (path, body) => request("PATCH", path, body);
|
|
const del = (path, body) => request("DELETE", path, body);
|
|
|
|
/** 失败时统一 toast,并把错误抛回去让调用方决定是否中断。 */
|
|
function toastError(e) {
|
|
wx.showToast({ title: (e && e.message) || "出错了", icon: "none", duration: 2500 });
|
|
}
|
|
|
|
/** 没登录就去登录页。 */
|
|
function requireLogin() {
|
|
const app = getApp();
|
|
if (!app.globalData.token) {
|
|
wx.reLaunch({ url: "/pages/login/login" });
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/** 没孩子档案就去建档页。 */
|
|
function requireChild() {
|
|
if (!requireLogin()) return false;
|
|
const app = getApp();
|
|
if (!app.globalData.child) {
|
|
wx.reLaunch({ url: "/pages/children/children" });
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
module.exports = { request, get, post, patch, del, toastError, requireLogin, requireChild, token };
|