You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
1.5 KiB
76 lines
1.5 KiB
// 云函数getSecondhandGoods
|
|
const cloud = require('wx-server-sdk')
|
|
|
|
// 初始化cloud
|
|
cloud.init({
|
|
env: cloud.DYNAMIC_CURRENT_ENV
|
|
})
|
|
const db = cloud.database()
|
|
const _ = db.command
|
|
|
|
exports.main = async (event, context) => {
|
|
// 从请求中获取参数
|
|
const {
|
|
category = 'all',
|
|
keyword = '',
|
|
pageNum = 1,
|
|
pageSize = 10,
|
|
sortBy = 'createTime'
|
|
} = event
|
|
|
|
// 构建查询条件
|
|
let query = {}
|
|
|
|
// 根据分类筛选
|
|
if (category !== 'all') {
|
|
query.category = category
|
|
}
|
|
|
|
// 根据关键词搜索标题
|
|
if (keyword) {
|
|
query.title = db.RegExp({
|
|
regexp: keyword,
|
|
options: 'i',
|
|
})
|
|
}
|
|
|
|
// 只查询未售出的商品
|
|
query.status = 'available'
|
|
|
|
// 计算总数
|
|
const countResult = await db.collection('secondhand_goods')
|
|
.where(query)
|
|
.count()
|
|
const total = countResult.total
|
|
|
|
// 构建排序条件
|
|
let orderBy = {}
|
|
switch(sortBy) {
|
|
case 'price':
|
|
orderBy = { price: 1 }
|
|
break
|
|
case 'price-desc':
|
|
orderBy = { price: -1 }
|
|
break
|
|
case 'createTime':
|
|
default:
|
|
orderBy = { createTime: -1 }
|
|
}
|
|
|
|
// 查询数据
|
|
const goods = await db.collection('secondhand_goods')
|
|
.where(query)
|
|
.orderBy(Object.keys(orderBy)[0], Object.values(orderBy)[0] > 0 ? 'asc' : 'desc')
|
|
.skip((pageNum - 1) * pageSize)
|
|
.limit(pageSize)
|
|
.get()
|
|
|
|
return {
|
|
success: true,
|
|
data: goods.data,
|
|
total,
|
|
pageNum,
|
|
pageSize,
|
|
hasMore: total > pageNum * pageSize
|
|
}
|
|
}
|