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

51 lines
1.4 KiB
TypeScript

import san from "sanitize-html";
import { messages } from "~/lib/server/constants";
import isLoggedIn from "~/lib/server/middlewareButNotReally/isLoggedIn";
import { Story } from "~/models/stories";
import { Review } from "~/models/stories/review";
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 (
replyingTo?.author.blocked.includes(ev.context.currentUser!._id) ||
ev.context.currentUser!.blocked.includes(replyingTo?.author._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(),
});
let nrs = await newReply.save();
replyingTo.replies.push(nrs._id);
await replyingTo.save();
const story = await Story.findById(replyingTo.leftOn);
return {
back: `/story/${replyingTo.leftOn}/${
story!.chapters.findIndex((x) => x.id === nrs.whichChapter) + 1
}`,
data: nrs.toObject(),
success: true,
};
});