From f95ce018e1dcc00360205c3b1e7e49d7897d1234 Mon Sep 17 00:00:00 2001 From: Apoorv Mishra Date: Wed, 26 Jul 2023 18:15:56 +0530 Subject: [PATCH] perf: cache response --- plugins/iframely/server/iframely.ts | 52 +++++++++++++++++++++++------ 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/plugins/iframely/server/iframely.ts b/plugins/iframely/server/iframely.ts index 3a359f1c5..e84b858ae 100644 --- a/plugins/iframely/server/iframely.ts +++ b/plugins/iframely/server/iframely.ts @@ -1,22 +1,54 @@ import fetch from "fetch-with-proxy"; import env from "@server/env"; -import { InvalidRequestError } from "@server/errors"; +import { InternalError } from "@server/errors"; +import Redis from "@server/redis"; class Iframely { private static apiUrl = `${env.IFRAMELY_URL}/api`; private static apiKey = env.IFRAMELY_API_KEY; + private static cacheKeyPrefix = "unfurl"; - public static async get(url: string, type = "oembed") { - try { - const res = await fetch( - `${this.apiUrl}/${type}?url=${encodeURIComponent(url)}&api_key=${ - this.apiKey - }` + private static cacheKey(url: string) { + return `${this.cacheKeyPrefix}-${url}`; + } + + private static async cache(url: string) { + const data = await this.fetch(url); + + if (!data.error) { + await Redis.defaultClient.set( + this.cacheKey(url), + JSON.stringify(data), + "EX", + data.cache_age ); - const data = await res.json(); - return data; + } + + return data; + } + + private static async fetch(url: string, type = "oembed") { + const res = await fetch( + `${this.apiUrl}/${type}?url=${encodeURIComponent(url)}&api_key=${ + this.apiKey + }` + ); + return res.json(); + } + + private static async cached(url: string) { + const val = await Redis.defaultClient.get(this.cacheKey(url)); + if (val) { + return JSON.parse(val); + } + } + + public static async get(url: string) { + try { + const cached = await this.cached(url); + return cached ? cached : this.cache(url); } catch (err) { - throw InvalidRequestError(err); + throw InternalError(err); } } }