Files
kycnotme/web/src/pages/ogimage.png.ts

37 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-05-20 01:47:50 +00:00
import { ogImageTemplates, type OgImageAllTemplatesWithProps } from '../components/OgImage'
2025-05-19 10:23:36 +00:00
import type { APIRoute } from 'astro'
2025-05-20 01:47:50 +00:00
import type { Misc } from 'ts-toolbelt'
2025-05-19 10:23:36 +00:00
2025-05-20 01:47:50 +00:00
function toJSON<T extends Misc.JSON.Value>(data: string | null | undefined): T | undefined {
if (!data) return undefined
try {
return JSON.parse(data) as T
} catch (_error) {
return undefined
}
}
export const GET: APIRoute = async (context) => {
const { template, ...props } = toJSON<OgImageAllTemplatesWithProps>(
context.url.searchParams.get('data')
) ?? { template: 'default' }
2025-05-19 10:23:36 +00:00
2025-05-20 01:47:50 +00:00
if (!template as unknown) return ogImageTemplates.default({}, context)
2025-05-19 10:23:36 +00:00
if (!(template in ogImageTemplates)) {
console.error(`Invalid template: "${template}"`)
2025-05-19 22:13:13 +00:00
return ogImageTemplates.default({}, context)
2025-05-19 10:23:36 +00:00
}
2025-05-20 01:47:50 +00:00
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
const response = await ogImageTemplates[template](props as any, context)
2025-05-19 10:23:36 +00:00
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!response) {
console.error(`Cannot generate image for template: ${template} and props: ${JSON.stringify(props)}`)
2025-05-19 22:13:13 +00:00
return ogImageTemplates.default({}, context)
2025-05-19 10:23:36 +00:00
}
return response
}