以“获取文章评论列表”功能为例子,分以下几个步骤完成:
1、根据文章id获取评论列表(评论需要分页,所以还需page,limit参数);
2、评论有上下级关系(回复评论),循环获取子评论;
3、获取评论的用户信息;
4、时间格式化(小程序云服务器提供的系统时间需要进行格式化,如不需要可)
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
exports.main = async(event, context) => {
// 获取评论列表
let {
id,
page,
limit
} = event;
let base_data = [];
const db = cloud.database()
const db_comment = db.collection('comment');
const db_user = db.collection('user');
// 获取评论
let comments = await (db_comment.where({
article_id: id,
comment_id: null
}).orderBy('created_at', 'desc')
.skip(limit * (page - 1))
.limit(limit)
.get());
for (let i = 0; i < comments.data.length; i++) {
// 获取子评论
let comments_children = await (db_comment.where({
article_id: id,
comment_id: comments.data[i]._id
}).orderBy('created_at', 'asc')
.skip(0)
.limit(9)
.get());
let _children = [];
for (let i = 0; i < comments_children.data.length; i++) {
// 获取用户
let user = await (db_user.where({
openid: comments_children.data[i].openid
}).get())
// 时间格式化
let created_at = utc2beijing(comments_children.data[i].created_at, 'yyyy-MM-dd hh:mm');
comments_children.data[i].created_at = created_at;
let info = user.data[0].info;
info['openId'] = user.data[0].openid;
_children.push({
comment: comments_children.data[i],
user: info
})
}
comments.data[i]['children'] = _children;
// 获取用户
let user = await (db_user.where({
openid: comments.data[i].openid
}).get())
// 时间格式化
let created_at = utc2beijing(comments.data[i].created_at, 'yyyy-MM-dd hh:mm');
comments.data[i].created_at = created_at;
base_data.push({
comment: comments.data[i],
user: user.data[0].info
})
}
return base_data;
/**
* 时间转换
*/
function utc2beijing(utc_datetime, format) {
let timestamp = utc_datetime.getTime();
// 增加8个小时,北京时间比utc时间多八个时区
timestamp = timestamp + 8 * 60 * 60 * 1000;
return dateFormat((parseInt(timestamp)), format);
}
function dateFormat(timestamp, format) {
if (!format) {
format = "yyyy-MM-dd hh:mm:ss";
}
timestamp = parseInt(timestamp);
var realDate = new Date(timestamp);
function timeFormat(num) {
return num < 10 ? '0' + num : num;
}
var date = [
["M+", timeFormat(realDate.getMonth() + 1)],
["d+", timeFormat(realDate.getDate())],
["h+", timeFormat(realDate.getHours())],
["m+", timeFormat(realDate.getMinutes())],
["s+", timeFormat(realDate.getSeconds())],
["q+", Math.floor((realDate.getMonth() + 3) / 3)],
["S+", realDate.getMilliseconds()],
];
var regYear = new RegExp("(y+)", "i");
var reg1 = regYear.exec(format);
if (reg1) {
format = format.replace(reg1[1], (realDate.getFullYear() + '').substring(4 - reg1[1].length));
}
for (var i = 0; i < date.length; i++) {
var k = date[i][0];
var v = date[i][1];
var reg2 = new RegExp("(" + k + ")").exec(format);
if (reg2) {
format = format.replace(reg2[1], reg2[1].length == 1 ?
v : ("00" + v).substring(("" + v).length));
}
}
return format;
}
}