server / graphql /loaders.js
Mark-Lasfar
Add GraphQL
d100ebb
Raw
History Blame Contribute Delete
1.69 kB
// graphql/loaders.js
const DataLoader = require('dataloader');
const { User, Follow, Post } = require('../server');
const {mongoose } = require('mongoose');
const createLoaders = () => ({
// βœ… User Loader
userLoader: new DataLoader(async (userIds) => {
const users = await User.find({ _id: { $in: userIds } });
return userIds.map(id => users.find(u => u._id.toString() === id.toString()));
}),
// βœ… Followers Count Loader
followersCountLoader: new DataLoader(async (userIds) => {
const counts = await Follow.aggregate([
{ $match: { followingId: { $in: userIds.map(id => new mongoose.Types.ObjectId(id)) }, status: 'accepted' } },
{ $group: { _id: '$followingId', count: { $sum: 1 } } }
]);
return userIds.map(id => counts.find(c => c._id.toString() === id.toString())?.count || 0);
}),
// βœ… Following Count Loader
followingCountLoader: new DataLoader(async (userIds) => {
const counts = await Follow.aggregate([
{ $match: { followerId: { $in: userIds.map(id => new mongoose.Types.ObjectId(id)) }, status: 'accepted' } },
{ $group: { _id: '$followerId', count: { $sum: 1 } } }
]);
return userIds.map(id => counts.find(c => c._id.toString() === id.toString())?.count || 0);
}),
// βœ… Posts Count Loader
postsCountLoader: new DataLoader(async (userIds) => {
const counts = await Post.aggregate([
{ $match: { userId: { $in: userIds.map(id => new mongoose.Types.ObjectId(id)) } } },
{ $group: { _id: '$userId', count: { $sum: 1 } } }
]);
return userIds.map(id => counts.find(c => c._id.toString() === id.toString())?.count || 0);
}),
});
module.exports = { createLoaders };