refactor(api/utils): update listQuerier helper

make it return an object containing a sliced array and a total
This commit is contained in:
parent faaf385bde
commit 45783c60a9
Signed by: tablet
GPG Key ID: 924A5F6AF051E87C

@ -1,9 +1,19 @@
import { Band } from "~/models/band"; import { Band } from "~/models/band";
import { Challenge } from "~/models/challenges/gen"; import { Challenge } from "~/models/challenges/gen";
import { Story } from "~/models/stories"; import { IStory, Story } from "~/models/stories";
import { log } from "../logger"; import { log } from "../logger";
import { H3Event, EventHandlerRequest } from "h3";
export default async function (query, context, limit?: number, sort?) { export default async function (
query,
context,
ev: H3Event<EventHandlerRequest>,
limit: number = 0,
sort?,
): Promise<{ stories: IStory[]; total: number }> {
const q = getQuery(ev);
let skipAmt = limit * (parseInt((q.page as string) || "1") - 1) - 1;
if (skipAmt < 0) skipAmt = 0;
query["chapters.hidden"] = false; query["chapters.hidden"] = false;
if (context.currentUser) { if (context.currentUser) {
if (!query.author) query.author = {}; if (!query.author) query.author = {};
@ -14,7 +24,6 @@ export default async function (query, context, limit?: number, sort?) {
query["ficmas"] = { query["ficmas"] = {
$nin: context.ficmasarray_raw.map((a) => a._id), $nin: context.ficmasarray_raw.map((a) => a._id),
}; };
log.debug(query, { label: "list query" });
let stories = await Story.find(query, null) let stories = await Story.find(query, null)
.collation({ locale: "en" }) .collation({ locale: "en" })
.sort(sort ? sort : { "chapters.posted": -1 }) .sort(sort ? sort : { "chapters.posted": -1 })
@ -26,7 +35,11 @@ export default async function (query, context, limit?: number, sort?) {
.populate("chapters.bands") .populate("chapters.bands")
.populate({ path: "challenge", model: Challenge }) .populate({ path: "challenge", model: Challenge })
.populate("author", "username _id") .populate("author", "username _id")
.limit(limit || Infinity)
.exec(); .exec();
return stories.filter((a) => a.author != null); let oro = stories.filter((a) => a.author != null);
log.debug(JSON.stringify(query), { label: "list query" });
return {
total: oro.length,
stories: oro.slice(skipAmt, limit == 0 ? oro.length : skipAmt + limit),
};
} }