Cache rich media cards for 12 hours

This commit is contained in:
Alex Gleason 2023-05-06 20:30:11 -05:00
parent 78b1c24ee0
commit f567acb58f
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 18 additions and 2 deletions

View File

@ -30,3 +30,4 @@ import 'npm:linkify-plugin-hashtag@^4.1.0';
// @deno-types="npm:@types/mime@3.0.0"
export { default as mime } from 'npm:mime@^3.0.0';
export { unfurl } from 'npm:unfurl.js@^6.3.1';
export { default as TTLCache } from 'npm:@isaacs/ttlcache@^1.4.0';

View File

@ -1,4 +1,4 @@
import { findReplyTag, lodash, nip19, unfurl, z } from '@/deps.ts';
import { findReplyTag, lodash, nip19, TTLCache, unfurl, z } from '@/deps.ts';
import { type Event } from '@/event.ts';
import { type MetaContent, parseMetaContent } from '@/schema.ts';
@ -107,7 +107,7 @@ async function toStatus(event: Event<1>) {
return {
id: event.id,
account,
card: firstUrl ? await unfurlCard(firstUrl) : null,
card: firstUrl ? await unfurlCardCached(firstUrl) : null,
content: html,
created_at: new Date(event.created_at * 1000).toISOString(),
in_reply_to_id: replyTag ? replyTag[1] : null,
@ -196,4 +196,19 @@ async function unfurlCard(url: string): Promise<PreviewCard | null> {
}
}
const TWELVE_HOURS = 12 * 60 * 60 * 1000;
const previewCardCache = new TTLCache({ ttl: TWELVE_HOURS, max: 500 });
/** Unfurl card from cache if available, otherwise fetch it. */
async function unfurlCardCached(url: string): Promise<PreviewCard | null> {
const cached = previewCardCache.get<PreviewCard | null>(url);
if (cached !== undefined) return cached;
const card = await unfurlCard(url);
previewCardCache.set(url, card);
return card;
}
export { toAccount, toStatus };