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 }, );