// 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 };