feat(api): create endpoint to fetch all authors (users who have written >1 story)
This commit is contained in:
parent
f235d7da44
commit
dbc5cab712
50
server/api/authors.get.ts
Normal file
50
server/api/authors.get.ts
Normal file
@ -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 },
|
||||
);
|
Loading…
x
Reference in New Issue
Block a user