Skip to content

Commit

Permalink
Improve caching in link metadata so it doesn't fetch same link multip…
Browse files Browse the repository at this point in the history
…le times
  • Loading branch information
teodorus-nathaniel committed Aug 16, 2023
1 parent 4c2d4e7 commit 87bcff1
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/pages/api/posts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,26 @@ export async function getPostsServer(postIds: string[]): Promise<PostData[]> {
}

const filteredPosts = mergedPosts.filter((post) => !!post)
const promises = filteredPosts.map(async (post) => {
const linksToFetch = new Set<string>()
filteredPosts.forEach((post) => {
post.struct.ownerId = toSubsocialAddress(post.struct.ownerId)!
await addMetadataToPost(post)
if (post.content?.link) linksToFetch.add(post.content.link)
})

const metadataMap: Record<string, LinkMetadata> = {}
const metadataPromises = Array.from(linksToFetch).map(async (link) => {
const metadata = await getLinkMetadata(link)
if (metadata) metadataMap[link] = metadata
})
await Promise.allSettled(metadataPromises)

filteredPosts.forEach((post) => {
const link = post.content?.link
const linkMetadata = metadataMap[link ?? '']
if (!linkMetadata || !post.content) return

post.content.linkMetadata = linkMetadata
})
await Promise.all(promises)

return filteredPosts
}
Expand Down

0 comments on commit 87bcff1

Please sign in to comment.