Only call opengraph if needed
This commit is contained in:
parent
2a819c6d0c
commit
2c3e0253f6
1 changed files with 18 additions and 2 deletions
|
|
@ -11,6 +11,11 @@ function getOpenGraphClient(): any {
|
||||||
return openGraphClient
|
return openGraphClient
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function extractOgImageUrl(html: string): string {
|
||||||
|
const match = html.match(/<meta property="og:image" content="([^"]+)" \/>/)
|
||||||
|
return match?.[1] ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
export default defineEventHandler(async (event) => {
|
export default defineEventHandler(async (event) => {
|
||||||
const { cardUrl } = getQuery(event)
|
const { cardUrl } = getQuery(event)
|
||||||
|
|
||||||
|
|
@ -28,10 +33,21 @@ export default defineEventHandler(async (event) => {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let ogImageUrl = ''
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
|
||||||
|
// If no og:image was found, try to get it from opengraph.io
|
||||||
|
if (!ogImageUrl) {
|
||||||
const response = await getOpenGraphClient().getSiteInfo(cardUrl)
|
const response = await getOpenGraphClient().getSiteInfo(cardUrl)
|
||||||
|
|
||||||
const ogImageUrl = response?.openGraph?.image?.url ?? ''
|
ogImageUrl = response?.openGraph?.image?.url ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
console.log(JSON.stringify({ cardUrl, ogImageUrl }))
|
console.log(JSON.stringify({ cardUrl, ogImageUrl }))
|
||||||
|
|
||||||
await send(event, ogImageUrl)
|
await send(event, ogImageUrl)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue