next/server/api/story/[id]/[chapter]/index.put.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

58 lines
1.6 KiB
TypeScript

import { FormChapter } from "@client/types/form/story";
import { countWords } from "@functions";
import { messages } from "@server/constants";
import { storyQuerier } from "@server/dbHelpers";
import { isLoggedIn } from "@server/middlewareButNotReally";
import { canModify } from "@server/middlewareButNotReally/storyPrivileges";
import { replaceOrUploadContent, bodyHandler } from "@server/storyHelpers";
import { Story } from "@models/stories";
export default eventHandler(async (ev) => {
isLoggedIn(ev);
const story = await storyQuerier(ev);
if (!canModify(ev, story)) {
throw createError({
statusCode: 403,
message: messages[403],
});
}
const body = await readBody(ev);
const cc: FormChapter = body.chapters[0];
const cid = story.chapters[ev.context.chapterIndex].id;
const content = await bodyHandler(cc);
await replaceOrUploadContent(cid!, content);
let ns;
try {
ns = await Story.findOneAndUpdate(
{
"chapters.id": cid,
},
{
$set: {
"chapters.$.title": cc.chapterTitle,
"chapters.$.summary": cc.summary,
"chapters.$.characters": cc.characters,
"chapters.$.relationships": Array.from(new Set(cc.relationships)),
"chapters.$.bands": cc.bands,
"chapters.$.nsfw": cc.nsfw,
"chapters.$.notes": cc.notes,
"chapters.$.words": countWords(content),
"chapters.$.genre": cc.genre,
"chapters.$.loggedInOnly": cc.loggedInOnly,
},
},
{ new: true },
);
} catch (e: any) {
throw createError({
statusCode: 500,
message: e.toString(),
});
}
return {
data: ns,
message: "Chapter updated",
succes: true,
};
});