mirror of
https://github.com/khairul169/code-share.git
synced 2025-04-28 16:49:36 +07:00
feat: add caching to thumbnail creator
This commit is contained in:
parent
fc1c1f4e29
commit
06b864055c
@ -1,24 +1,44 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import { screenshot } from "../lib/screenshot";
|
import { screenshot } from "../lib/screenshot";
|
||||||
|
|
||||||
const cache = new Map<string, Buffer>();
|
const cache = new Map<string, { data: Buffer; timestamp: number }>();
|
||||||
|
|
||||||
export const thumbnail = async (req: Request, res: Response) => {
|
const regenerateThumbnail = async (slug: string) => {
|
||||||
const { slug } = req.params;
|
const curCache = cache.get(slug);
|
||||||
const cacheData = cache.get(slug);
|
|
||||||
|
|
||||||
if (cacheData) {
|
if (curCache?.data) {
|
||||||
res.contentType("image/jpeg");
|
cache.set(slug, {
|
||||||
return res.send(cacheData);
|
data: curCache.data,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await screenshot(slug);
|
const result = await screenshot(slug);
|
||||||
if (!result) {
|
if (!result) {
|
||||||
return res.status(400).send("Cannot generate thumbnail!");
|
return curCache;
|
||||||
}
|
}
|
||||||
|
|
||||||
cache.set(slug, result);
|
const data = {
|
||||||
|
data: result,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
cache.set(slug, data);
|
||||||
|
return data;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const thumbnail = async (req: Request, res: Response) => {
|
||||||
|
const { slug } = req.params;
|
||||||
|
let cacheData = cache.get(slug);
|
||||||
|
|
||||||
|
if (!cacheData) {
|
||||||
|
cacheData = await regenerateThumbnail(slug);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cacheData && Date.now() - cacheData.timestamp > 10000) {
|
||||||
|
regenerateThumbnail(slug);
|
||||||
|
}
|
||||||
|
|
||||||
res.contentType("image/jpeg");
|
res.contentType("image/jpeg");
|
||||||
res.send(result);
|
res.send(cacheData?.data);
|
||||||
};
|
};
|
||||||
|
@ -28,6 +28,7 @@ export const screenshot = async (slug: string) => {
|
|||||||
|
|
||||||
closeHandler = setTimeout(() => {
|
closeHandler = setTimeout(() => {
|
||||||
browser?.close();
|
browser?.close();
|
||||||
|
browser = null;
|
||||||
closeHandler = null;
|
closeHandler = null;
|
||||||
}, 60000);
|
}, 60000);
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user