mirror of
https://github.com/khairul169/code-share.git
synced 2026-10-24 11:53:58 +07:00
feat: add project thumbnail generator
This commit is contained in:
@@ -1,10 +1,13 @@
|
||||
import { Router } from "express";
|
||||
import preview from "./preview";
|
||||
import trpc from "./trpc/handler";
|
||||
import { thumbnail } from "./thumbnail";
|
||||
|
||||
const api = Router();
|
||||
|
||||
api.use("/trpc", trpc);
|
||||
api.use("/preview", preview);
|
||||
|
||||
api.get("/thumbnail/:slug", thumbnail);
|
||||
|
||||
export default api;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Request, Response } from "express";
|
||||
import { screenshot } from "../lib/screenshot";
|
||||
|
||||
const cache = new Map<string, Buffer>();
|
||||
|
||||
export const thumbnail = async (req: Request, res: Response) => {
|
||||
const { slug } = req.params;
|
||||
const cacheData = cache.get(slug);
|
||||
|
||||
if (cacheData) {
|
||||
res.contentType("image/jpeg");
|
||||
return res.send(cacheData);
|
||||
}
|
||||
|
||||
const result = await screenshot(slug);
|
||||
if (!result) {
|
||||
return res.status(400).send("Cannot generate thumbnail!");
|
||||
}
|
||||
|
||||
cache.set(slug, result);
|
||||
|
||||
res.contentType("image/jpeg");
|
||||
res.send(result);
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
import puppeteer, { Browser } from "puppeteer";
|
||||
|
||||
let browser: Browser | null = null;
|
||||
let closeHandler: any;
|
||||
|
||||
export const screenshot = async (slug: string) => {
|
||||
try {
|
||||
if (!browser) {
|
||||
browser = await puppeteer.launch({
|
||||
headless: true,
|
||||
args: ["--no-sandbox"],
|
||||
});
|
||||
}
|
||||
|
||||
const page = await browser.newPage();
|
||||
|
||||
await page.setViewport({ width: 512, height: 340 });
|
||||
await page.goto(`http://localhost:3000/api/preview/${slug}/index.html`, {
|
||||
waitUntil: "networkidle0",
|
||||
timeout: 5000,
|
||||
});
|
||||
const result = await page.screenshot();
|
||||
await page.close();
|
||||
|
||||
if (closeHandler) {
|
||||
clearTimeout(closeHandler);
|
||||
}
|
||||
|
||||
closeHandler = setTimeout(() => {
|
||||
browser?.close();
|
||||
closeHandler = null;
|
||||
}, 60000);
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user