diff --git a/lib/server/dbHelpers/chapterTransformer.ts b/lib/server/dbHelpers/chapterTransformer.ts new file mode 100644 index 0000000..f10fb7c --- /dev/null +++ b/lib/server/dbHelpers/chapterTransformer.ts @@ -0,0 +1,31 @@ +import { H3Event, EventHandlerRequest } from "h3"; +import { GridFSBucket } from "mongodb"; +import mongoose, { Document } from "mongoose"; +import { stringifyStream } from "~/lib/functions"; +import { IStory } from "~/models/stories"; +import { IChapter } from "~/models/stories/chapter"; +import getBucket from "../storyHelpers/getBucket"; + +export default async function ( + story: Document & IStory, + event: H3Event, +) { + const finObj: any = story.toObject(); + const cloned: any & { chapters: IChapter[] } = { ...finObj }; + delete finObj.chapters; + const bucket = getBucket(); + let ds = bucket.openDownloadStreamByName( + `/stories/${cloned.chapters[event.context.chapterIndex || 0].id}.txt`, + ); + let stream = await stringifyStream(ds); + finObj.currentChapter = { + ...cloned.chapters[event.context.chapterIndex || 0], + text: stream + .replace(/\n/g, "
") + .replace(/

/gm, "

") + .replace(/

 <\/p>/gm, "") + .replace(/

<\/p>/gm, ""), + }; + finObj.totalChapters = story.chapters.length; + return finObj; +}