Files
kenyang d780f905bb feat(user-merge): 双用户体系行为合并 — 会员资料计入共拆分析 + 等级统一「非会员」标注
后端:
- /ai/collaboration-analysis 平台资料不足时自动合并拆书帮会员资料
  (tags/description/分舵/城市计入完善度,AI prompt 附会员身份)
  修复:杨珂鸣分析刘艳红误报「资料不足」,现 78 分推荐
- /chaishu/members/:uid 详情路由补 boundUserId/boundNickname/boundAvatar/boundPosition
- 等级措辞统一:非拆书家→非会员(AI prompt + 存量数据已修正)

前端:
- 新增 pages/chaishu-member-detail 会员名片页:未入驻→「邀请 TA 使用拆约」分享;
  已入驻→「邀请 TA 共拆」跳协作分析
- home onBuddyTap / chaishu-members onMemberTap:未绑定会员跳名片页(原误跳会员列表/toast)
- profile/activity-detail:非会员灰显「非会员」无徽章;edit-profile 选项更新
- app.js verifyUserExists 网络异常不再清登录态;clearLoginInfo 对齐 clearLoginState
- home/more-activities handleQuickJoin catch 补 silent 检查,修「报名误弹请登录」
2026-11-15 05:32:18 +08:00

252 lines
6.8 KiB
JavaScript

// utils/request.js - 微信小程序网络请求封装
const app = getApp();
const { config } = require('../config');
const API_BASE_URL = config.apiBaseUrl;
// 将 snake_case 转换为 camelCase
const toCamelCase = (str) => {
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
};
// 递归转换对象的所有 key 为 camelCase
const transformKeysToCamelCase = (obj) => {
if (obj === null || obj === undefined) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(transformKeysToCamelCase);
}
if (typeof obj === 'object' && obj.constructor === Object) {
const transformed = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
transformed[toCamelCase(key)] = transformKeysToCamelCase(obj[key]);
}
}
return transformed;
}
return obj;
};
// 将 camelCase 转换为 snake_case
const toSnakeCase = (str) => {
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
};
// 递归转换对象的 key 为 snake_case
const transformKeysToSnakeCase = (obj) => {
if (obj === null || obj === undefined) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(transformKeysToSnakeCase);
}
if (typeof obj === 'object' && obj.constructor === Object) {
const transformed = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
transformed[toSnakeCase(key)] = transformKeysToSnakeCase(obj[key]);
}
}
return transformed;
}
return obj;
};
/**
* 发起网络请求
* @param {string} url - 请求地址
* @param {string} method - 请求方法
* @param {object} data - 请求数据
* @param {object} options - 其他选项
*/
const request = (url, method = 'GET', data = {}, options = {}) => {
const {
showLoading = true,
loadingText = '加载中...',
showError = true,
} = options;
return new Promise((resolve, reject) => {
// 显示加载中
if (showLoading) {
wx.showLoading({
title: loadingText,
mask: true,
});
}
const token = wx.getStorageSync('token');
const userId = wx.getStorageSync('userId');
const header = {
'Content-Type': 'application/json; charset=utf-8',
...options.header,
};
if (token) {
header['Authorization'] = `Bearer ${token}`;
}
if (userId) {
header['x-user-id'] = userId;
}
// 转换请求数据 key 为 snake_case
const requestData = transformKeysToSnakeCase(data);
// 显式 JSON.stringify 避免小程序自动序列化时的编码问题
const jsonData = JSON.stringify(requestData);
wx.request({
url: `${API_BASE_URL}${url}`,
method,
data: jsonData,
header,
timeout: options.timeout || 10000,
success: (res) => {
if (showLoading) {
wx.hideLoading();
}
if (res.statusCode === 200) {
// 转换响应数据 key 为 camelCase
const transformedData = transformKeysToCamelCase(res.data);
// 邮箱未绑定拦截:统一弹窗引导去「编辑资料」绑定邮箱
if (transformedData && transformedData.code === 'EMAIL_REQUIRED') {
wx.showModal({
title: '请先绑定邮箱',
content: transformedData.message || '邮箱是身份认定凭证,绑定后即可继续操作',
confirmText: '去绑定',
cancelText: '暂不',
success: (r) => {
if (r.confirm) {
wx.navigateTo({ url: '/pages/edit-profile/index?focus=email' });
}
},
});
reject({ ...transformedData, silent: true });
return;
}
resolve(transformedData);
} else if (res.statusCode === 401) {
// 未授权:静默清除登录状态,不强制跳转登录页,由用户后续操作时自主选择登录
app.clearLoginInfo();
wx.removeStorageSync('token');
wx.removeStorageSync('userId');
wx.removeStorageSync('isLoggedIn');
reject({ message: '登录已过期,请重新登录', silent: true });
} else {
if (showError) {
wx.showToast({
title: res.data?.message || '请求失败',
icon: 'none',
});
}
reject(res.data || { message: '请求失败' });
}
},
fail: (err) => {
if (showLoading) {
wx.hideLoading();
}
if (showError) {
wx.showToast({
title: err.errMsg || '网络错误',
icon: 'none',
});
}
reject(err);
},
});
});
};
// 封装常用请求方法
const get = (url, data, options) => request(url, 'GET', data, options);
const post = (url, data, options) => request(url, 'POST', data, options);
const put = (url, data, options) => request(url, 'PUT', data, options);
const del = (url, data, options) => request(url, 'DELETE', data, options);
/**
* 上传文件
* @param {string} url - 上传地址
* @param {string} filePath - 文件路径
* @param {string} name - 文件对应的 key
* @param {object} formData - 其他表单数据
*/
const uploadFile = (url, filePath, name = 'file', formData = {}) => {
return new Promise((resolve, reject) => {
wx.showLoading({
title: '上传中...',
mask: true,
});
const token = wx.getStorageSync('token');
const userId = wx.getStorageSync('userId');
const header = {};
if (token) {
header['Authorization'] = `Bearer ${token}`;
}
if (userId) {
header['x-user-id'] = userId;
}
wx.uploadFile({
url: `${API_BASE_URL}${url}`,
filePath,
name,
formData: transformKeysToSnakeCase(formData),
header,
timeout: 30000,
success: (res) => {
wx.hideLoading();
if (res.statusCode === 200) {
try {
const data = JSON.parse(res.data);
resolve(transformKeysToCamelCase(data));
} catch (e) {
console.error('上传响应解析失败:', res.data);
wx.showToast({ title: '上传失败', icon: 'none' });
reject({ message: '上传失败' });
}
} else {
console.error('上传返回非200:', res.statusCode, res.data);
wx.showToast({
title: '上传失败',
icon: 'none',
});
reject({ message: '上传失败' });
}
},
fail: (err) => {
wx.hideLoading();
console.error('wx.uploadFile fail:', JSON.stringify(err));
wx.showToast({
title: err.errMsg || '上传失败',
icon: 'none',
});
reject(err);
},
});
});
};
module.exports = {
request,
get,
post,
put,
del,
uploadFile,
};