Skip to content

Commit

Permalink
feat: Added cache for link preview result (close #1316)
Browse files Browse the repository at this point in the history
  • Loading branch information
edgardmessias committed Aug 28, 2023
1 parent ac172a2 commit e19d4a6
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/util/linkPreview.ts
Expand Up @@ -41,12 +41,19 @@ const apiServers = config.linkPreviewApiServers || defaultApiServers;
const thumbHeight = 100;
const thumbWidth = 140;

const cache: { [key: string]: any } = {};

shuffleArray(apiServers);

/**
* Fetch preview link data from a remote server
*/
export async function fetchRemoteLinkPreviewData(url: string) {
if (cache[url]) {
debug(`Link preview found in the cache`, url);
return;
}

const textDecoder = new TextDecoder();

for (let i = apiServers.length - 1; i >= 0; i--) {
Expand Down Expand Up @@ -75,7 +82,7 @@ export async function fetchRemoteLinkPreviewData(url: string) {

const isVideo = /^video/.test(data.mediaType);

return {
const result = {
title: data.title,
description: data.description,
canonicalUrl: data.url,
Expand All @@ -84,6 +91,14 @@ export async function fetchRemoteLinkPreviewData(url: string) {
doNotPlayInline: !isVideo,
imageUrl: data.image,
};

cache[url] = result;

setTimeout(() => {
delete cache[url];
}, 300000); // 5 minutes

return result;
}

return null;
Expand Down

0 comments on commit e19d4a6

Please sign in to comment.