Skip to content

Commit

Permalink
Merge pull request #1004 from hackclub/malted/img
Browse files Browse the repository at this point in the history
Create a stats image endpoint
  • Loading branch information
malted authored Dec 22, 2024
2 parents 9ea765c + 5d64935 commit 308633b
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"next": "14.2.13",
"next-plausible": "^3.12.2",
"openai": "^4.68.4",
"puppeteer": "^23.11.1",
"react": "^18",
"react-dom": "^18",
"react-fast-marquee": "^1.6.5",
Expand Down
73 changes: 73 additions & 0 deletions src/app/api/stats/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import puppeteer from 'puppeteer'
import Airtable from 'airtable'

const base = new Airtable({ apiKey: process.env.AIRTABLE_API_KEY }).base(
process.env.BASE_ID!,
)

const html = (shipCount: number) => `
<!DOCTYPE html>
<html>
<head>
<style>
html, body { margin: 0 }
main { display: flex; flex-direction: column; align-items: center; }
h1 { font-family: sans-serif; text-align: center; }
</style>
</head>
<body>
<main>
<h1>${shipCount} projects shipped</h1>
</main>
</body>
</html>`

export async function GET() {
const [browser, ships] = await Promise.all([
puppeteer.launch({
headless: 'new',
args: ['--no-sandbox', '--disable-setuid-sandbox'],
}),
base('ships').select({}).all(),
])

try {
const page = await browser.newPage()

await page.setViewport({
width: 800,
height: 100,
deviceScaleFactor: 3,
})

await page.setContent(html(ships.length))

const screenshot = await page.screenshot({
type: 'png',
clip: {
x: 0,
y: 0,
width: 800,
height: 100,
},
})

await browser.close()

// Return the screenshot as a PNG
return new Response(screenshot, {
headers: {
'Content-Type': 'image/png',
// "Cache-Control": "public, max-age=3600"
},
})
} catch (error) {
await browser.close()
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: {
'Content-Type': 'application/json',
},
})
}
}

0 comments on commit 308633b

Please sign in to comment.