perf(api): convert handler for 'total stories+authors' endpoint to a cachedEventHandler
This commit is contained in:
parent
74b541df75
commit
e1fa6ab0a8
@ -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 },
|
||||
);
|
||||
|
Loading…
x
Reference in New Issue
Block a user