diff --git a/lib/utils/farcaster-helpers.js b/lib/utils/farcaster-helpers.js new file mode 100644 index 000000000..c35ec2f26 --- /dev/null +++ b/lib/utils/farcaster-helpers.js @@ -0,0 +1,79 @@ +// @flow + +import { FCCache } from './fc-cache.js'; + +type BaseFCInfo = { + +fid?: ?string, + +farcasterUsername?: ?string, + ... +}; +export type GetFCNames = ( + users: $ReadOnlyArray, +) => Promise; + +async function getFCNames( + fcCache: FCCache, + users: $ReadOnlyArray, +): Promise { + const info = users.map(user => { + if (!user) { + return user; + } + const { fid, farcasterUsername } = user; + let cachedResult = null; + if (farcasterUsername) { + cachedResult = farcasterUsername; + } else if (fid) { + cachedResult = fcCache.getCachedFarcasterUsernameForFID(fid); + } + return { + input: user, + fid, + cachedResult, + }; + }); + + const needFetch = info + .map(user => { + if (!user) { + return null; + } + const { fid, cachedResult } = user; + if (cachedResult || !fid) { + return null; + } + return fid; + }) + .filter(Boolean); + + const farcasterUsernames = new Map(); + if (needFetch.length > 0) { + const results = await fcCache.getFarcasterUsernamesForFIDs(needFetch); + for (let i = 0; i < needFetch.length; i++) { + const fid = needFetch[i]; + const result = results[i]; + if (result) { + farcasterUsernames.set(fid, result); + } + } + } + + return info.map(user => { + if (!user) { + return user; + } + const { input, fid, cachedResult } = user; + if (cachedResult) { + return { ...input, farcasterUsername: cachedResult }; + } else if (!fid) { + return input; + } + const farcasterUsername = farcasterUsernames.get(fid); + if (farcasterUsername) { + return { ...input, farcasterUsername }; + } + return input; + }); +} + +export { getFCNames };