优化列表刷新加载

This commit is contained in:
Dev
2026-10-19 13:01:58 +08:00
parent 0c6f4177f1
commit 44405743bb
10 changed files with 438 additions and 274 deletions
+137 -87
View File
@@ -1,6 +1,5 @@
import dayjs from 'dayjs';
var api = require('../config/api.js');
var util = require('../utils/util.js');
const formatTime = (date, template) => dayjs(date).format(template);
@@ -55,63 +54,147 @@ function testMobile(num) {
}
}
const REQUEST_TIMEOUT = 15000;
let tokenCache = '';
let tokenLoaded = false;
let reloginTask = null;
function getAppSafe() {
try {
return getApp();
} catch (err) {
return null;
}
}
/** 内存缓存 token,避免每次请求都读 Storage */
function getToken() {
if (!tokenLoaded) {
tokenCache = wx.getStorageSync('token') || '';
tokenLoaded = true;
}
return tokenCache;
}
function setToken(token) {
tokenCache = token || '';
tokenLoaded = true;
if (tokenCache) {
wx.setStorageSync('token', tokenCache);
} else {
wx.removeStorageSync('token');
}
}
/**
* 封封微信的的request
* 本地还没有 token 时,等冷启动登录结束再发需要鉴权的请求
* 已有 token 则直接发,过期由 401 重登处理
*/
function request(url, data = {}, method = "GET") {
return new Promise(function (resolve, reject) {
wx.request({
url: url,
data: data,
method: method,
header: {
'Content-Type': 'application/json',
// 'XDEBUG_TRIGGER': 'true',
'token': wx.getStorageSync('token')
},
success: function (res) {
if (res.statusCode == 200) {
function ensureLogin() {
if (getToken()) {
return Promise.resolve();
}
const app = getAppSafe();
if (app && app.loginReady) {
return app.loginReady;
}
return Promise.resolve();
}
if (res.data.errno == 401) {
//需要登录后才可以操作
function isUnauthorized(statusCode, body) {
return statusCode === 401 || !!(body && body.code === 401);
}
// let code = null;
// return login().then((res) => {
// code = res.code;
// return getUserInfo();
// }).then((userInfo) => {
// //登录远程服务器
// request(api.AuthLoginByWeixin, {
// code: code,
// userInfo: userInfo
// }, 'POST').then(res => {
// if (res.errno === 0) {
// //存储用户信息
// wx.setStorageSync('userInfo', res.data.userInfo);
// wx.setStorageSync('token', res.data.token);
// resolve(res);
// } else {
// reject(res);
// }
// }).catch((err) => {
// reject(err);
// });
// }).catch((err) => {
// reject(err);
// })
} else {
resolve(res.data);
}
} else {
reject(res.errMsg);
/** 登录失效后重新换 token,进行中的重登合并成一次 */
function relogin() {
const app = getAppSafe();
if (app && app.loggingIn && app.loginReady) {
return app.loginReady.then(() => !!getToken());
}
if (reloginTask) {
return reloginTask;
}
reloginTask = login()
.then((wxRes) => request(api.AuthLoginByWeixin, { code: wxRes.code }, 'POST', { auth: false }))
.then((res) => {
if (res && res.code === 1 && res.data && res.data.token) {
setToken(res.data.token);
if (res.data.userinfo) {
wx.setStorageSync('userInfo', res.data.userinfo);
}
},
fail: function (err) {
reject(err)
return true;
}
return false;
})
.catch((err) => {
console.error('relogin failed:', err);
return false;
})
.then((ok) => {
reloginTask = null;
return ok;
});
return reloginTask;
}
/**
* 统一请求
* @param {string} url
* @param {object} data
* @param {string} method
* @param {{auth?: boolean, timeout?: number, retried?: boolean}} options
* auth 默认 true:没有 token 时等待登录,401 时重登并重试一次
* auth 为 false:免登录接口(分类、首页配置等)立即发送,不等待登录
*/
function request(url, data = {}, method = 'GET', options = {}) {
const auth = options.auth !== false;
const timeout = options.timeout || REQUEST_TIMEOUT;
const retried = !!options.retried;
const send = () => new Promise((resolve, reject) => {
const header = { 'Content-Type': 'application/json' };
const token = getToken();
if (token) {
header.token = token;
}
wx.request({
url,
data,
method,
timeout,
header,
success(res) {
const body = res.data && typeof res.data === 'object'
? res.data
: { code: 0, msg: '网络异常', data: null };
if (res.statusCode === 200 || isUnauthorized(res.statusCode, body)) {
resolve({ unauthorized: isUnauthorized(res.statusCode, body), body });
return;
}
reject((body && body.msg) || res.errMsg || '网络异常');
},
fail(err) {
reject(err);
},
});
});
const dispatch = () => send().then((result) => {
if (result.unauthorized && auth && !retried) {
return relogin().then((ok) => {
if (!ok) {
return result.body;
}
return request(url, data, method, { auth: true, timeout, retried: true });
});
}
return result.body;
});
if (!auth) {
return dispatch();
}
return ensureLogin().then(dispatch);
}
/**
@@ -194,40 +277,6 @@ function showSuccessToast(msg) {
})
}
function sentRes(url, data, method, fn) {
data = data || null;
if (data == null) {
var content = require('querystring').stringify(data);
} else {
var content = JSON.stringify(data); //json format
}
var parse_u = require('url').parse(url, true);
var isHttp = parse_u.protocol == 'http:';
var options = {
host: parse_u.hostname,
port: parse_u.port || (isHttp ? 80 : 443),
path: parse_u.path,
method: method,
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(content, "utf8"),
'Trackingmore-Api-Key': '1b70c67e-d191-4301-9c05-a50436a2526d'
}
};
var req = require(isHttp ? 'http' : 'https').request(options, function (res) {
var _data = '';
res.on('data', function (chunk) {
_data += chunk;
});
res.on('end', function () {
fn != undefined && fn(_data);
});
});
req.write(content);
req.end();
}
function loginNow() {
let userInfo = wx.getStorageSync('userInfo');
if (userInfo == '') {
@@ -235,10 +284,10 @@ function loginNow() {
success: (res) => {
request(api.AuthLoginByWeixin, {
code: res.code
}, 'POST').then(function (res) {
}, 'POST', { auth: false }).then(function (res) {
if (res.code === 1) {
let userInfo = res.data.userInfo;
wx.setStorageSync('token', res.data.token);
setToken(res.data.token);
wx.setStorageSync('userInfo', userInfo);
}
});
@@ -563,6 +612,8 @@ module.exports = {
phoneRegCheck,
formatTimeNum: formatTimeNum,
request,
getToken,
setToken,
redirect,
showErrorToast,
showSuccessToast,
@@ -570,7 +621,6 @@ module.exports = {
login,
getUserInfo,
testMobile,
sentRes,
loginNow,
getTextLength,
transferBorder,