vercel-og-with-tweaks/pages/api/dynamic-image.tsx

110 lines
2.8 KiB
TypeScript
Raw Permalink Normal View History

2022-11-04 23:02:31 +00:00
import { ImageResponse } from '@vercel/og'
import { NextRequest } from 'next/server'
2022-11-05 13:03:04 +00:00
import fetch from 'node-fetch';
2022-11-04 23:02:31 +00:00
export const config = {
runtime: 'experimental-edge',
}
2022-11-05 13:03:04 +00:00
const TITLE = "Measure is unceasing"
const getHiTitle = (body, i) => {
console.log(`Getting h${i}`)
let hi = `h${i}`
let regex = new RegExp(hi + "\>(.*)\<\/" + hi)
console.log(regex)
let his = body.split("\n").filter(line => line.includes(`<${hi}>`))
for (let line of his) {
let regexOutput = regex.exec(line)
if (regexOutput != null) {
let regexMatch = regexOutput[1]
if (regexMatch != TITLE && !regexMatch.includes(TITLE)) {
return regexMatch
}
}
}
return TITLE
}
const getTitle = body => {
let bestH1match = getHiTitle(body, 1)
if (bestH1match == TITLE) {
let bestH2match = getHiTitle(body, 2)
return bestH2match
}
return bestH1match
}
const getFirstImgurImage = body => {
let lines = body.split("\n").filter(line => line.includes('img src="https://i.imgur.com/'))
if (lines.length > 0) {
let regex = new RegExp('img src="https://i.imgur.com/(.*?)"')
let regexOutput = regex.exec(lines[0])
if (regexOutput != null) {
let regexMatch = regexOutput[1]
let imgurUrl = `https://i.imgur.com/${regexMatch}`
console.log(imgurUrl)
return imgurUrl
}
}
}
2022-11-04 23:02:31 +00:00
export default async function handler(req: NextRequest) {
const { searchParams } = req.nextUrl
2022-11-05 13:03:04 +00:00
const endpoint = searchParams.get('endpoint')
console.log(searchParams)
if (!endpoint) {
return new ImageResponse(<>{'Try with "?endpoint=blog/2022/09/02/simple-estimation-examples-in-squiggle/"'}</>, {
2022-11-04 23:02:31 +00:00
width: 1200,
height: 630,
})
}
2022-11-05 13:03:04 +00:00
const response = await fetch(`https://nunosempere.com/${endpoint}`);
const body = await response.text();
// Ah fuck it, I'll just use a regex.
//
let title = getTitle(body)
console.log(title)
let image = getFirstImgurImage(body)
2022-11-04 23:02:31 +00:00
return new ImageResponse(
(
<div
style={{
fontSize: 60,
color: 'black',
background: '#f6f6f6',
width: '100%',
height: '100%',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
display: 'flex',
2022-11-05 13:03:04 +00:00
paddingTop: 40
2022-11-04 23:02:31 +00:00
}}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
alt="avatar"
2022-11-05 13:03:04 +00:00
height="400"
src={image || "https://i.imgur.com/5uk7LBH.png"}
2022-11-04 23:02:31 +00:00
style={{
2022-11-05 13:03:04 +00:00
borderRadius: 0,
2022-11-04 23:02:31 +00:00
}}
/>
2022-11-05 13:03:04 +00:00
<h1 style={{ fontSize: "50px", paddingBottom: 0, }}>{title || "Measure is unceasing"}</h1>
<h2 style={{ fontSize: "30px", paddingTop: 0, }}>nunosempere.com/{endpoint}</h2>
2022-11-04 23:02:31 +00:00
</div>
),
{
width: 1200,
height: 630,
}
)
}