This example will showcase how to read data from the Farcaster network using the
official hub-nodejs in typescript.We will create a simple feed of casts from a list of FIDs and display them in reverse chronological order.
First, let’s set up some constants and create a client to connect to the hub.
Copy
Ask AI
import { getSSLHubRpcClient } from '@farcaster/hub-nodejs';/** * Populate the following constants with your own values */const HUB_URL = 'hoyt.farcaster.xyz:3383'; // URL of the Hubconst FIDS = [2, 3]; // User IDs to fetch casts for// const client = getInsecureHubRpcClient(HUB_URL); // Use this if you're not using SSLconst client = getSSLHubRpcClient(HUB_URL);
The raw cast data is not very readable. We’ll write a function to convert the timestamp to a human readable format, and
also resolve any mentions (only stored as fids and their location within the cast) to their fnames.
Copy
Ask AI
const castToString = async ( cast: CastAddMessage, nameMapping: Map<number, string>, client: HubRpcClient) => { const fname = nameMapping.get(cast.data.fid) ?? `${cast.data.fid}!`; // if the user doesn't have a username set, use their FID // Convert the timestamp to a human readable string const unixTime = fromFarcasterTime(cast.data.timestamp)._unsafeUnwrap(); const dateString = timeAgo.format(new Date(unixTime)); const { text, mentions, mentionsPositions } = cast.data.castAddBody; const bytes = new TextEncoder().encode(text); const decoder = new TextDecoder(); let textWithMentions = ''; let indexBytes = 0; for (let i = 0; i < mentions.length; i++) { textWithMentions += decoder.decode( bytes.slice(indexBytes, mentionsPositions[i]) ); const result = await getFnameFromFid(mentions[i], client); result.map((fname) => (textWithMentions += fname)); indexBytes = mentionsPositions[i]; } textWithMentions += decoder.decode(bytes.slice(indexBytes)); // Remove newlines from the message text const textNoLineBreaks = textWithMentions.replace(/(\r\n|\n|\r)/gm, ' '); return `${fname}: ${textNoLineBreaks}\n${dateString}\n`;};