From dbc5cab712c3b205c358a60eddee8d2fdf1fee08 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, 10 Oct 2023 22:14:44 -0400 Subject: [PATCH] feat(api): create endpoint to fetch all authors (users who have written >1 story) --- server/api/authors.get.ts | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 server/api/authors.get.ts diff --git a/server/api/authors.get.ts b/server/api/authors.get.ts new file mode 100644 index 0000000..84b9042 --- /dev/null +++ b/server/api/authors.get.ts @@ -0,0 +1,50 @@ +import { User } from "~/models/user"; +let authorSingleton: { + lastRefreshed: number; + data: { + username: string; + _id: number; + numStories: number; + }[]; +} = { + data: [], + lastRefreshed: Date.now(), +}; + +const threshold = 60 * 60 * 1000; +export default cachedEventHandler( + async (ev) => { + if ( + Date.now() - authorSingleton.lastRefreshed >= threshold || + authorSingleton.data.length < 1 + ) + authorSingleton.data = await User.aggregate([ + { $project: { username: true, _id: true } }, + { + $lookup: { + from: "stories", + localField: "_id", + foreignField: "author", + as: "stories", + }, + }, + { $set: { numStories: { $size: "$stories" } } }, + { $unset: "stories" }, + { + $match: { + numStories: { $gte: 1 }, + _id: { $nin: ev.context.currentUser?.hiddenAuthors || [] }, + }, + }, + ]); + authorSingleton.data.sort((a, b) => { + if (a.username.toLocaleUpperCase() > b.username.toLocaleUpperCase()) + return 1; + else if (a.username.toLocaleUpperCase() < b.username.toLocaleUpperCase()) + return -1; + return 0; + }); + return authorSingleton.data; + }, + { maxAge: 60 * 60 * 3 }, +);