From 2c3e0253f664bf042a9e12537bd6700767c8bf89 Mon Sep 17 00:00:00 2001 From: Shinigami92 Date: Mon, 12 Dec 2022 16:00:26 +0100 Subject: [PATCH] Only call opengraph if needed --- server/api/og-image.ts | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/server/api/og-image.ts b/server/api/og-image.ts index 0d94289e..5b4cf445 100644 --- a/server/api/og-image.ts +++ b/server/api/og-image.ts @@ -11,6 +11,11 @@ function getOpenGraphClient(): any { return openGraphClient } +function extractOgImageUrl(html: string): string { + const match = html.match(//) + return match?.[1] ?? '' +} + export default defineEventHandler(async (event) => { const { cardUrl } = getQuery(event) @@ -28,10 +33,21 @@ export default defineEventHandler(async (event) => { }) } - const response = await getOpenGraphClient().getSiteInfo(cardUrl) + let ogImageUrl = '' - const ogImageUrl = response?.openGraph?.image?.url ?? '' + // First we want to try to get the og:image from the html + // But sometimes it is not included due to async JS loading + const html = await $fetch(cardUrl) + ogImageUrl = extractOgImageUrl(html) + // If no og:image was found, try to get it from opengraph.io + if (!ogImageUrl) { + const response = await getOpenGraphClient().getSiteInfo(cardUrl) + + ogImageUrl = response?.openGraph?.image?.url ?? '' + } + + // eslint-disable-next-line no-console console.log(JSON.stringify({ cardUrl, ogImageUrl })) await send(event, ogImageUrl)