| |
| const DataLoader = require('dataloader'); |
| const { User, Follow, Post } = require('../server'); |
| const {mongoose } = require('mongoose'); |
|
|
| const createLoaders = () => ({ |
| |
| 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())); |
| }), |
| |
| |
| 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); |
| }), |
| |
| |
| 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); |
| }), |
| |
| |
| 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 }; |