···105105106106 async getFollowsFollowing(viewerDid: string, subjectDids: string[]) {
107107 /*
108108- * 1. Get all the people Alice is following
109109- * 2. Get all the people Dan is followed by
110110- * 3. Find the intersection
108108+ * Find people the viewer follows who also follow each subject.
109109+ * Uses aggregation to avoid fetching all followers of popular accounts.
111110 */
112111113112 const results: FollowsFollowing[] = [];
114113115115- for (const subjectDid of subjectDids) {
116116- // Get people who follow the subject (Dan's followers)
117117- const subjectFollowers = await this.db.models.Follow.find({
118118- subject: subjectDid,
119119- });
114114+ // Get all people the viewer follows (bounded by viewer's follow count)
115115+ const viewerFollows = await this.db.models.Follow.find({
116116+ authorDid: viewerDid,
117117+ }).select("subject");
118118+119119+ const viewerFollowsDids = viewerFollows.map((f) => f.subject);
120120121121- const followerDids = subjectFollowers.map((f) => f.authorDid);
121121+ if (viewerFollowsDids.length === 0) {
122122+ // Viewer follows no one, so no known followers possible
123123+ return {
124124+ results: subjectDids.map((targetDid) =>
125125+ new FollowsFollowing({ targetDid, dids: [] })
126126+ ),
127127+ };
128128+ }
122129123123- // Find which of these followers Alice also follows
130130+ for (const subjectDid of subjectDids) {
131131+ // Find which of the viewer's follows also follow the subject
132132+ // This query is bounded by the viewer's follow count, not the subject's follower count
124133 const mutualConnections = await this.db.models.Follow.find({
125125- authorDid: viewerDid,
126126- subject: { $in: followerDids },
127127- });
134134+ authorDid: { $in: viewerFollowsDids },
135135+ subject: subjectDid,
136136+ }).select("authorDid");
128137129138 results.push(
130139 new FollowsFollowing({
131140 targetDid: subjectDid,
132132- dids: mutualConnections.map((connection) => connection.subject),
141141+ dids: mutualConnections.map((connection) => connection.authorDid),
133142 }),
134143 );
135144 }