diff --git a/server/api/totals.get.ts b/server/api/totals.get.ts index 8d3a5c2..ffc7ed2 100644 --- a/server/api/totals.get.ts +++ b/server/api/totals.get.ts @@ -1,10 +1,47 @@ import mongoose from "mongoose"; import { Story } from "~/models/stories"; +import { User } from "~/models/user"; -export default eventHandler(async (event) => { - let aa = mongoose.connection.db.collection("z_index_totAuthors"); - let totalStories = await Story.countDocuments({ "chapters.hidden": false }); - let totalAuthors = await aa.countDocuments(); +let authorSingleton: { + lastRefreshed: number; + data: { + username: string; + _id: number; + numStories: number; + }[]; +} = { + data: [], + lastRefreshed: Date.now(), +}; - return { stories: totalStories, authors: totalAuthors }; -}); +const threshold = 60 * 60 * 1000; + +export default cachedEventHandler( + async (event) => { + let aa = mongoose.connection.db.collection("z_index_totAuthors"); + let totalStories = await Story.countDocuments({ "chapters.hidden": false }); + if ( + !authorSingleton.data.length || + Date.now() - authorSingleton.lastRefreshed >= threshold + ) { + 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 } } }, + ]); + } + let totalAuthors = authorSingleton.data.length; + + return { stories: totalStories, authors: totalAuthors }; + }, + { maxAge: 60 * 60 * 24 }, +);