diff --git a/lib/utils/neynar-client.js b/lib/utils/neynar-client.js --- a/lib/utils/neynar-client.js +++ b/lib/utils/neynar-client.js @@ -14,7 +14,7 @@ +result: { +users: $ReadOnlyArray, +next: { - +cursor: string, + +cursor: ?string, }, }, }; @@ -46,37 +46,45 @@ } // We're using the term "friend" for a bidirectional follow - async fetchFriendFIDs(fid: string): Promise { + async fetchFriendFIDs(fid: string): Promise<$ReadOnlyArray> { const fids = []; - const params: { [string]: string } = { - fid, - viewerFid: fid, - limit: fetchFollowerLimit.toString(), - }; - while (true) { + let paginationCursor = null; + + do { + const params: { [string]: string } = { + fid, + viewerFid: fid, + limit: fetchFollowerLimit.toString(), + ...(paginationCursor ? { cursor: paginationCursor } : null), + }; + const url = getNeynarURL('1', 'followers', params); - const response = await fetch(url, { - method: 'GET', - headers: { - Accept: 'application/json', - api_key: this.apiKey, - }, - }); - const json: FetchFollowersResponse = await response.json(); - const { users } = json.result; - for (const user of users) { - if (!user.viewerContext.following) { - continue; + + try { + const response = await fetch(url, { + method: 'GET', + headers: { + Accept: 'application/json', + api_key: this.apiKey, + }, + }); + + const json: FetchFollowersResponse = await response.json(); + const { users } = json.result; + + for (const user of users) { + if (user.viewerContext.following) { + fids.push(user.fid.toString()); + } } - fids.push(user.fid.toString()); - } - if (users.length < fetchFollowerLimit) { - return fids; + + paginationCursor = json.result.next.cursor; + } catch (error) { + throw new Error(`Failed to fetch friend FIDs: ${error}`); } - params.cursor = json.result.next.cursor; - } - // eslint-disable-next-line no-unreachable - throw new Error('should not get here'); + } while (paginationCursor); + + return fids; } }