next/server/api/story/[id]/index.put.ts
☙◦ The Tablet ❀ GamerGirlandCo ◦❧ 05d11e0ea5
refactor(api): change stuff in story updating route
if the story doesn't exist/is null, throw
ensure chapter word count is updated (since we weren't already doing that for some reason....)
instead of clearing the original story's chapters and re-adding them one by one, update the existing ones in place, otherwise push to the array
use new signature for `replaceOrUploadContent` call
ensure chapters are sorted
2024-07-09 21:10:03 -04:00

76 lines
2.0 KiB
TypeScript

import { Document } from "mongoose";
import { IStory, Story } from "@models/stories";
import { FormStory } from "@client/types/form/story";
import { storyQuerier } from "@server/dbHelpers";
import { isLoggedIn } from "@server/middlewareButNotReally";
import { canModify } from "@server/middlewareButNotReally/storyPrivileges";
import { bodyHandler, getBucket, modelFormChapter, replaceOrUploadContent } from "@server/storyHelpers";
import { countWords } from "@functions";
import { messages } from "@server/constants";
export default eventHandler(async (ev) => {
let os: (Document<unknown, {}, IStory> & IStory) | null = await storyQuerier(ev);
isLoggedIn(ev);
if (!os) {
throw createError({
statusCode: 404,
message: messages[404],
});
}
if (!canModify(ev, os)) {
throw createError({
statusCode: 403,
message: messages[403],
});
}
const body: FormStory = await readBody<FormStory>(ev);
const update: Partial<IStory> = {
title: body.title,
completed: body.completed,
coAuthor: !!body.coAuthor ? body.coAuthor : null,
};
for (const c of body.chapters) {
let idx = os.chapters.findIndex((k) => k.id === c.id);
const cont = await bodyHandler(c);
if (idx === -1) {
os.chapters!.push({
...modelFormChapter(c),
words: countWords(cont),
posted: new Date(Date.now()),
});
} else {
os.chapters[idx] = {
...modelFormChapter(c),
id: os.chapters[idx].id,
words: countWords(cont),
posted: os.chapters[idx].posted,
};
}
}
os.chapters.sort((a, b) => a.index - b.index);
await os.save();
for (let i = 0; i < os.chapters.length; i++) {
const c = os.chapters[i];
const cont = await bodyHandler(body.chapters[i]);
await replaceOrUploadContent(c.id ?? c._id, cont, getBucket());
}
os = await Story.findOneAndUpdate(
{
_id: os._id,
},
update,
{ new: true },
);
if (!os) {
throw createError({
statusCode: 500,
message: "Something went wrong.",
});
}
return {
success: true,
story: os.toObject(),
};
});