From 2f72c03fd9236ad7ce4dc0ebc38128167f2aa324 Mon Sep 17 00:00:00 2001 From: Shinigami92 Date: Mon, 12 Dec 2022 16:53:43 +0100 Subject: [PATCH] pass url as path variable --- components/status/StatusPreviewCard.vue | 4 +-- server/api/{og-image.ts => og-image/[url].ts} | 28 +++++++++++++++---- 2 files changed, 23 insertions(+), 9 deletions(-) rename server/api/{og-image.ts => og-image/[url].ts} (73%) diff --git a/components/status/StatusPreviewCard.vue b/components/status/StatusPreviewCard.vue index 9e2d74ac..a79aba94 100644 --- a/components/status/StatusPreviewCard.vue +++ b/components/status/StatusPreviewCard.vue @@ -22,9 +22,7 @@ watch(cardImage, (image) => { imageSrc.value = image if (image) { - $fetch('/api/og-image', { - params: { cardUrl: props.card.url }, - }).then((ogImageUrl) => { + $fetch(`/api/og-image/${encodeURIComponent(props.card.url)}`).then((ogImageUrl) => { // eslint-disable-next-line no-console console.log('ogImageUrl', ogImageUrl) diff --git a/server/api/og-image.ts b/server/api/og-image/[url].ts similarity index 73% rename from server/api/og-image.ts rename to server/api/og-image/[url].ts index 44ee9bf9..c300e15f 100644 --- a/server/api/og-image.ts +++ b/server/api/og-image/[url].ts @@ -22,8 +22,23 @@ function extractOgImageUrl(html: string): string { return match?.[1] ?? '' } +async function resolveOgImageUrlManually(cardUrl: string): Promise { + const html = await $fetch(cardUrl) + + const ogImageUrl = extractOgImageUrl(html) + + if (!ogImageUrl) { + // Throw an error so we can try to apply another fallback + throw new Error('Could not find og:image in html.') + } + + return ogImageUrl +} + export default defineEventHandler(async (event) => { - const { cardUrl } = getQuery(event) + const { url } = getRouterParams(event) + + const cardUrl = decodeURIComponent(url) if (!cardUrl) { throw createError({ @@ -39,16 +54,17 @@ export default defineEventHandler(async (event) => { }) } - let ogImageUrl = '' - + // If anything goes wrong, fail gracefully try { // 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) + let ogImageUrl = await resolveOgImageUrlManually(cardUrl).catch(() => + // Try another fallback + '', + ) if (process.env.NUXT_OPENGRAPH_API) { - // If no og:image was found, try to get it from opengraph.io + // If no og:image was found, try to get it from opengraph.io if (!ogImageUrl) { const response = await getOpenGraphClient().getSiteInfo(cardUrl)