diff --git a/server/api/story/[id]/index.put.ts b/server/api/story/[id]/index.put.ts index 79cd177..9b2add9 100644 --- a/server/api/story/[id]/index.put.ts +++ b/server/api/story/[id]/index.put.ts @@ -11,6 +11,12 @@ import { messages } from "@server/constants"; export default eventHandler(async (ev) => { let os: (Document & IStory) | null = await storyQuerier(ev); isLoggedIn(ev); + if (!os) { + throw createError({ + statusCode: 404, + message: messages[404], + }); + } if (!canModify(ev, os)) { throw createError({ statusCode: 403, @@ -23,39 +29,31 @@ export default eventHandler(async (ev) => { completed: body.completed, coAuthor: !!body.coAuthor ? body.coAuthor : null, }; - for (const oc of os.chapters) { - let filename = `/stories/${oc.id}.txt`; - const bucket = getBucket(); - const curs = bucket.find({ filename }).limit(1); - for await (const d of curs) { - await bucket.delete(d._id); - } - } - const cc = os.chapters; - os.chapters = []; - await os.save(); + for (const c of body.chapters) { - let idx = cc.findIndex((k) => k.id === c.id); + 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!.push({ + os.chapters[idx] = { ...modelFormChapter(c), - // id: os.chapters[idx].id, + id: os.chapters[idx].id, words: countWords(cont), - posted: cc[idx].posted, - }); + 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); + await replaceOrUploadContent(c.id ?? c._id, cont, getBucket()); } os = await Story.findOneAndUpdate( {