feat(api): change route and allow choosing the format
This commit is contained in:
@@ -2,30 +2,39 @@ import { createCanvas, loadImage } from "canvas";
|
||||
import QRCode from "qrcode";
|
||||
import { z } from "zod";
|
||||
import { resolve } from "path";
|
||||
import sharp from "sharp";
|
||||
|
||||
const time = (label: string) => {
|
||||
const start = performance.now();
|
||||
return () => {
|
||||
console.log(label, "\t", performance.now() - start);
|
||||
console.log(`${label}\t${performance.now() - start}`);
|
||||
};
|
||||
};
|
||||
|
||||
const querySchema = z.object({
|
||||
const IMAGE_FORMATS = ["jpeg", "png", "webp"] as const;
|
||||
|
||||
const settingsSchema = z.object({
|
||||
format: z.enum(IMAGE_FORMATS).default("png"),
|
||||
logo: z.string().min(1),
|
||||
content: z.string().min(1),
|
||||
});
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const parsed = querySchema.safeParse(getQuery(event));
|
||||
const query = getQuery(event);
|
||||
|
||||
const parsed = settingsSchema.safeParse(query);
|
||||
if (!parsed.success) {
|
||||
return createError({
|
||||
status: 400,
|
||||
message: `Invalid request query: missing ${parsed.error.errors.map((x) => x.path.join(".")).join(", ")}`,
|
||||
data: {
|
||||
errors: Object.fromEntries(
|
||||
parsed.error.errors.map((x) => [x.path.join("."), x.message]),
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const logo = parsed.data.logo;
|
||||
const text = parsed.data.content;
|
||||
const { format, logo, content } = parsed.data;
|
||||
|
||||
const tt = time("total");
|
||||
let t;
|
||||
@@ -35,7 +44,7 @@ export default defineEventHandler(async (event) => {
|
||||
|
||||
t = time("render");
|
||||
const canvas = createCanvas(SIZE, SIZE);
|
||||
await QRCode.toCanvas(canvas, text, {
|
||||
await QRCode.toCanvas(canvas, content, {
|
||||
errorCorrectionLevel: "H",
|
||||
width: SIZE,
|
||||
margin: 1,
|
||||
@@ -43,7 +52,7 @@ export default defineEventHandler(async (event) => {
|
||||
t();
|
||||
|
||||
t = time("count");
|
||||
const qrCode = QRCode.create(text, { errorCorrectionLevel: "H" });
|
||||
const qrCode = QRCode.create(content, { errorCorrectionLevel: "H" });
|
||||
const moduleCount = qrCode.modules.size + 2;
|
||||
t();
|
||||
|
||||
@@ -75,11 +84,18 @@ export default defineEventHandler(async (event) => {
|
||||
t();
|
||||
|
||||
t = time("buffer");
|
||||
const image = canvas.toBuffer();
|
||||
let image = canvas.toBuffer();
|
||||
t();
|
||||
|
||||
if (format !== "png") {
|
||||
t = time("convert");
|
||||
image = await sharp(image).toFormat(format).toBuffer();
|
||||
t();
|
||||
}
|
||||
|
||||
tt();
|
||||
|
||||
event.node.res.setHeader("Content-Type", "image/png");
|
||||
event.node.res.setHeader("Content-Type", `image/${format}`);
|
||||
return image;
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user