pass url as path variable

This commit is contained in:
Shinigami92 2022-12-12 16:53:43 +01:00
parent 26bc4e7251
commit 2f72c03fd9
2 changed files with 23 additions and 9 deletions

View file

@ -22,9 +22,7 @@ watch(cardImage, (image) => {
imageSrc.value = image
if (image) {
$fetch<string>('/api/og-image', {
params: { cardUrl: props.card.url },
}).then((ogImageUrl) => {
$fetch<string>(`/api/og-image/${encodeURIComponent(props.card.url)}`).then((ogImageUrl) => {
// eslint-disable-next-line no-console
console.log('ogImageUrl', ogImageUrl)

View file

@ -22,8 +22,23 @@ function extractOgImageUrl(html: string): string {
return match?.[1] ?? ''
}
async function resolveOgImageUrlManually(cardUrl: string): Promise<string> {
const html = await $fetch<string>(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,13 +54,14 @@ 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<string>(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