refactor(server/utils): add transformer for regular chapter objects
this transforms a story object into a slightly different object to be served by the api. notable differences are the `totalChapters` field and the removal of the `chapters` array. `chapters` is then replaced by a `currentChapter` object, representing the currently "selected" chapter, with an added `text` field
This commit is contained in:
		
							parent
							
								
									c8bdcc0ec3
								
							
						
					
					
						commit
						66d6168a31
					
				
							
								
								
									
										31
									
								
								lib/server/dbHelpers/chapterTransformer.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										31
									
								
								lib/server/dbHelpers/chapterTransformer.ts
									
									
									
									
									
										Normal file
									
								
							| @ -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<number, {}, IStory> & IStory, | ||||
| 	event: H3Event<EventHandlerRequest>, | ||||
| ) { | ||||
| 	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, "<br>") | ||||
| 			.replace(/<br><p>/gm, "<p>") | ||||
| 			.replace(/<p> <\/p>/gm, "") | ||||
| 			.replace(/<p><br\s\/><b\s\/><\/p>/gm, ""), | ||||
| 	}; | ||||
| 	finObj.totalChapters = story.chapters.length; | ||||
| 	return finObj; | ||||
| } | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user