From dd9fcaf5aea42fd5a36eaa7f68dc9aae332ee4b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=98=99=E2=97=A6=20The=20Tablet=20=E2=9D=80=20GamerGirla?= =?UTF-8?q?ndCo=20=E2=97=A6=E2=9D=A7?= Date: Tue, 3 Oct 2023 00:52:24 -0400 Subject: [PATCH] refactor(api/utils): add story query helper function to avoid having to write the same `populate` calls over and over --- lib/server/dbHelpers/storyQuerier.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 lib/server/dbHelpers/storyQuerier.ts diff --git a/lib/server/dbHelpers/storyQuerier.ts b/lib/server/dbHelpers/storyQuerier.ts new file mode 100644 index 0000000..5cb07e5 --- /dev/null +++ b/lib/server/dbHelpers/storyQuerier.ts @@ -0,0 +1,23 @@ +import type { H3Event, EventHandlerRequest } from "h3"; +import { Challenge } from "~/models/challenges/gen"; +import { Story } from "~/models/stories"; +export default async function (ev: H3Event) { + const id = parseInt(getRouterParam(ev, "id") as string); + const chapterIndex = ev.context.chapterIndex; + if (isNaN(id) || isNaN(chapterIndex)) + throw createError({ + statusCode: 404, + message: "Not found.", + }); + const story = await Story.findById(id) + .populate("author", "username profile blocked") + .populate("chapters.bands") + .populate({ + path: "ficmas", + populate: { path: "wisher", select: "_id username" }, + }) + .populate({ path: "challenge", model: Challenge }) + .exec(); + if (!story) throw createError({ statusCode: 404, message: "Not found." }); + return story; +}