next/server/api/review/[id]/reply.post.ts
☙◦ The Tablet ❀ GamerGirlandCo ◦❧ 1447960b1a
refactor(db/models): update populatedDoc types
- remove `& Document` qualifier
- cast `T | number` to T with the `as` keyword
2023-12-29 19:06:55 -05:00

62 lines
1.6 KiB
TypeScript

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 (
(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();
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 {
back: `/story/${replyingTo.leftOn}/${
story!.chapters.findIndex((x) => x.id === nrs.whichChapter) + 1
}`,
data: nrs.toObject(),
success: true,
};
});