elk/server/api/og-image.ts

31 lines
753 B
TypeScript
Raw Normal View History

2022-12-12 16:26:30 +03:00
// This API-Endpoint will be cached via nuxt.config.ts -> nitro.routeRules['/api/og-image'].cache.maxAge = 86400
function extractOgImageUrl(html: string): string {
const match = html.match(/<meta property="og:image" content="([^"]+)" \/>/)
return match?.[1] ?? ''
}
2022-12-11 01:09:11 +03:00
export default defineEventHandler(async (event) => {
const { cardUrl } = getQuery(event)
if (!cardUrl) {
throw createError({
statusCode: 422,
statusMessage: 'Missing cardUrl.',
})
}
if (typeof cardUrl !== 'string') {
throw createError({
statusCode: 422,
statusMessage: 'cardUrl must be string.',
})
}
2022-12-12 16:26:30 +03:00
const html = await $fetch<string>(cardUrl)
const ogImageUrl = extractOgImageUrl(html)
2022-12-11 01:09:11 +03:00
await send(event, ogImageUrl)
})
2022-12-12 16:26:30 +03:00