From 87bcff129bf8951908cf470a3c02deb7a1ee9133 Mon Sep 17 00:00:00 2001 From: TeodorusNathaniel Date: Wed, 16 Aug 2023 19:06:30 +0700 Subject: [PATCH] Improve caching in link metadata so it doesn't fetch same link multiple times --- src/pages/api/posts.ts | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/pages/api/posts.ts b/src/pages/api/posts.ts index b2299aaef..6b6622424 100644 --- a/src/pages/api/posts.ts +++ b/src/pages/api/posts.ts @@ -108,11 +108,26 @@ export async function getPostsServer(postIds: string[]): Promise { } const filteredPosts = mergedPosts.filter((post) => !!post) - const promises = filteredPosts.map(async (post) => { + const linksToFetch = new Set() + 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 = {} + 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 }