Files
ai_dianshang/miniprogram/services/comments/fetchComments.js

80 lines
2.8 KiB
JavaScript
Raw Normal View History

2025-11-17 14:11:46 +08:00
const { config } = require('../../config/index');
/** 获取商品评论 */
function mockFetchComments(parmas) {
const { delay } = require('../_utils/delay');
const { getGoodsAllComments } = require('../../model/comments');
return delay().then(() => getGoodsAllComments(parmas));
}
/** 获取商品评论 */
function fetchComments(params) {
if (config.useMock) {
return mockFetchComments(params);
}
const { productId, page = 1, pageSize = 10, rating, hasImages } = params;
console.log('[fetchComments] 接收到的参数:', params);
console.log('[fetchComments] productId:', productId, '类型:', typeof productId);
// 验证productId参数
if (productId === null || productId === undefined || productId === '' || productId === 'undefined' || productId === 'null') {
console.error('[fetchComments] 商品ID为空或无效:', productId);
return Promise.reject(new Error('商品ID不能为空'));
}
// 确保productId是数字
const numericProductId = Number(productId);
console.log('[fetchComments] 转换后的数字ID:', numericProductId);
if (isNaN(numericProductId) || numericProductId <= 0) {
console.error('[fetchComments] 商品ID不是有效的正整数:', productId, '->', numericProductId);
return Promise.reject(new Error('商品ID必须是有效的正整数'));
}
return new Promise((resolve, reject) => {
wx.request({
url: `${config.apiBase}/comments/products/${numericProductId}`,
method: 'GET',
data: {
page,
page_size: pageSize,
rating,
has_images: hasImages
},
success: (res) => {
if (res.statusCode === 200 && res.data.code === 200) {
// 转换数据格式以匹配前端期望的结构
const result = {
pageNum: res.data.data.page,
pageSize: res.data.data.page_size,
totalCount: res.data.data.total.toString(),
comments: res.data.data.list.map(comment => ({
id: comment.id,
product_id: comment.product_id,
user_id: comment.user_id,
user_name: comment.user_name || '匿名用户',
user_avatar: comment.user_avatar || 'https://tdesign.gtimg.com/miniprogram/template/retail/avatar/avatar1.png',
rating: comment.rating,
content: comment.content,
images: comment.images || [],
is_anonymous: comment.is_anonymous || false,
reply_content: comment.reply_content || '',
created_at: comment.created_at,
product_spec: comment.product_spec || ''
}))
};
resolve(result);
} else {
reject(new Error(res.data.message || '获取评论失败'));
}
},
fail: (err) => {
reject(err);
}
});
});
}
module.exports = { fetchComments };