celo-poll/lib/feed/generator.ts
2025-12-08 16:31:30 +03:00

70 lines
2.1 KiB
TypeScript

import { redis } from '@/lib/redis'
export interface FeedItem {
id: string
type: 'vote' | 'comment' | 'poll_created' | 'follow'
userFid: string
username: string
pfpUrl?: string
pollId?: string
pollQuestion?: string
timestamp: number
content?: string
score: number
}
export async function generateFeed(fid: string, limit: number = 50): Promise<FeedItem[]> {
const following = await redis.smembers(`following:${fid}`)
if (!following || following.length === 0) return []
const items: FeedItem[] = []
const now = Date.now()
for (const followedFid of following) {
const userData = await redis.get(`user:${followedFid}`)
const user = userData ? (typeof userData === 'string' ? JSON.parse(userData) : userData) : {}
const votes = await redis.lrange(`votes:${followedFid}`, 0, 9)
for (const voteStr of votes) {
const vote = JSON.parse(voteStr)
const age = (now - vote.timestamp) / 3600000
const score = calculateScore(vote.timestamp, 1, age)
items.push({
id: `vote-${followedFid}-${vote.timestamp}`,
type: 'vote',
userFid: followedFid,
username: user.username || `User ${followedFid}`,
pfpUrl: user.pfpUrl,
pollId: vote.pollId,
pollQuestion: vote.pollQuestion || 'Poll',
timestamp: vote.timestamp,
score
})
}
}
items.sort((a, b) => b.score - a.score)
return items.slice(0, limit)
}
function calculateScore(timestamp: number, engagement: number, ageHours: number): number {
const recencyWeight = Math.exp(-ageHours / 24)
const engagementWeight = Math.log(engagement + 1)
return recencyWeight * 100 + engagementWeight * 10
}
export async function getFeedWithCursor(
fid: string,
cursor?: string,
limit: number = 20
): Promise<{ items: FeedItem[]; nextCursor?: string }> {
const allItems = await generateFeed(fid, 100)
const startIdx = cursor ? parseInt(cursor) : 0
const items = allItems.slice(startIdx, startIdx + limit)
const nextCursor = startIdx + limit < allItems.length ? String(startIdx + limit) : undefined
return { items, nextCursor }
}