next/server/api/review/[id]/reply.post.ts

56 lines
1.6 KiB
TypeScript
Raw Normal View History

import san from "sanitize-html";
import { messages } from "@server/constants";
import { isLoggedIn } from "@server/middlewareButNotReally";
import { Story } from "@models/stories";
import { Review } from "@models/stories/review";
import { IUser } from "@models/user";
export default eventHandler(async (ev) => {
isLoggedIn(ev);
const revid = parseInt(getRouterParam(ev, "revid")!);
let replyingTo = await Review.findOne({
_id: revid,
})
.populate("author", "username _id blocked")
.exec();
if (!replyingTo) {
throw createError({
statusCode: 404,
message: messages[404],
});
}
if (
2023-12-29 20:53:29 -05:00
(replyingTo?.author as IUser).blocked.includes(ev.context.currentUser!._id) ||
ev.context.currentUser!.blocked.includes((replyingTo?.author as IUser)._id)
) {
throw createError({
statusCode: 403,
message: "That didn't work",
});
}
const body = await readBody(ev);
const newReply = new Review({
author: ev.context.currentUser!._id,
replyingTo: revid,
text: san(body.content),
leftOn: replyingTo?.leftOn,
whichChapter: replyingTo.whichChapter,
datePosted: new Date(),
});
const { _id } = await newReply.save();
2023-12-29 20:53:29 -05:00
const nrs = (await Review.findOne({ _id }).populate("author", "username _id blocked").exec())!;
replyingTo.replies.push(nrs._id);
await replyingTo.save();
const story = await Story.findById(replyingTo.leftOn);
if (!story) {
throw createError({
statusCode: 404,
});
}
return {
2023-12-29 20:53:29 -05:00
back: `/story/${replyingTo.leftOn}/${story!.chapters.findIndex((x) => x.id === nrs.whichChapter) + 1}`,
data: nrs.toObject(),
success: true,
};
});