Files
ai_dianshang/miniprogram/services/good/fetchGoods.js
2025-11-17 14:11:46 +08:00

71 lines
2.0 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { config } from '../../config/index';
/** 获取商品列表 */
function mockFetchGoodsList(pageIndex = 1, pageSize = 20) {
const { delay } = require('../_utils/delay');
const { getGoodsList } = require('../../model/goods');
return delay().then(() =>
getGoodsList(pageIndex, pageSize).map((item) => {
return {
spuId: item.spuId,
thumb: item.primaryImage,
title: item.title,
price: item.minSalePrice,
originPrice: item.maxLinePrice,
tags: item.spuTagList.map((tag) => tag.title),
};
}),
);
}
/** 获取商品列表 */
export function fetchGoodsList(pageIndex = 1, pageSize = 20, categoryId = null) {
if (config.useMock) {
return mockFetchGoodsList(pageIndex, pageSize);
}
return new Promise((resolve, reject) => {
const requestData = {
page: pageIndex,
limit: pageSize,
};
// 如果有分类ID添加到请求参数中
if (categoryId) {
requestData.category_id = categoryId;
}
wx.request({
url: `${config.apiBase}/products`,
method: 'GET',
data: requestData,
success: (res) => {
if (res.statusCode === 200 && res.data.code === 200) {
// 转换API数据格式为小程序期望的格式
const products = res.data.data?.list || [];
const goodsList = products.map((item) => {
return {
spuId: item.id,
thumb: item.main_image,
title: item.name,
price: item.price,
originPrice: item.orig_price || item.price,
tags: [], // API暂时没有标签数据
stock: item.stock || 0, // 添加库存信息
isStock: item.stock > 0, // 添加库存状态
};
});
resolve(goodsList);
} else {
console.error('获取商品列表失败:', res.data);
resolve([]);
}
},
fail: (err) => {
console.error('商品列表请求失败:', err);
resolve([]);
}
});
});
}