server/laf-cloud/functions/comment.ts
2026-09-01 16:04:15 +08:00

133 lines
3.3 KiB
TypeScript

import cloud from '@lafjs/cloud'
const db = cloud.database();
import Utils from "@/Utils";
export default async function (ctx: FunctionContext) {
const action = ctx.body.action;
if (!action) {
return {
code: 0, data: null, msg: "action缺失"
}
}
const level = ctx.body.level;
if (!level) {
return {
code: 0, data: null, msg: "level缺失"
}
}
const pos = ctx.body.pos;
if (!pos) {
return {
code: 0, data: null, msg: "pos缺失"
}
}
const uid = ctx.body.uid;
let res = await db.collection("level" + pos).where({ level: level }).getOne();
let comment = res.data?.comment;
if (!comment) {
await db.collection("level" + pos).add({ level: level, comment: [] });
comment = [];
}
switch (action) {
case 'save':
let com = ctx.body.comment;
if (!com) {
return {
code: 0, data: null, msg: "请输入评论内容"
}
}
com = JSON.parse(com);
com.uid = uid;
com.like = 0;
let ishave = false;
let index = 0;
for (let i = 0; i < comment.length; i++) {
if (comment[i].uid == com.uid) {
index++;
}
}
if (index >= 3) {
return {
code: 0, data: null, msg: "评论数已达上限"
}
}
for (let i = 0; i < comment.length; i++) {
if (comment[i].uid == com.uid && comment[i].content == com.content) {
ishave = true;
}
}
if (ishave == false) {
com.index = comment.length;
comment.push(com);
let ret = await db.collection("level" + pos).where({ level: level }).update({ comment: comment });
return {
code: 1, data: null, msg: "评论更新成功"
}
} else {
return {
code: 0, data: null, msg: "请勿重复提交"
}
}
case 'read':
let list = [];
let index1 = 0;
let max = 0;
if (comment.length > 5) {
let list1 = [];
for (let i = 0; i < comment.length; i++) {
if (comment[i].like > max) {
index1 = i;
max = comment[i].like;
}
}
list1.push(index1);
if (comment.length > 50) {
while (list1.length < 5) {
let index2 = Math.floor(Math.random() * comment.length);
if (!list1.includes(index2)) {
list1.push(index2);
}
}
} else {
let m = comment.length - 1;
while (list1.length < 5) {
if (!list1.includes(m)) {
list1.push(m);
m--;
}
}
}
for (let i = 0; i < list1.length; i++) {
list.push(comment[list1[i]]);
}
} else {
list = comment;
}
return {
code: 1, data: {
comment: list
}, msg: "成功"
}
case 'like': {
const index = ctx.body.index;
if (!index && index != 0) {
return {
code: 0, data: null, msg: "请输入点赞id"
}
}
comment[index].like += 1;
let ret = await db.collection("level" + pos).where({ level: level }).update({ comment: comment });
return {
code: 1, data: null, msg: "成功"
}
}
default:
return {
code: 400,
message: '无效的操作类型,请使用 save 或 read'
}
}
}