next/server/api/totals.get.ts

45 lines
1.1 KiB
TypeScript
Raw Permalink Normal View History

2023-10-03 01:19:36 -04:00
import mongoose from "mongoose";
import { Story } from "@models/stories";
import { User } from "@models/user";
2023-10-03 01:19:36 -04:00
let authorSingleton: {
lastRefreshed: number;
data: {
username: string;
_id: number;
numStories: number;
}[];
} = {
data: [],
lastRefreshed: Date.now(),
};
2023-10-03 01:19:36 -04:00
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 });
2023-12-29 20:53:29 -05:00
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 },
);