All checks were successful
Deploy Production (qr.crewsportswear.app) / deploy (push) Successful in 35s
84 lines
2.1 KiB
JavaScript
84 lines
2.1 KiB
JavaScript
const express = require("express");
|
|
const QRCode = require("qrcode");
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
app.use(express.json({ limit: "100kb" }));
|
|
|
|
function parseIntWithBounds(value, fallback, min, max) {
|
|
const parsed = Number.parseInt(value, 10);
|
|
if (!Number.isFinite(parsed)) {
|
|
return fallback;
|
|
}
|
|
return Math.min(max, Math.max(min, parsed));
|
|
}
|
|
|
|
function normalizePayload(source) {
|
|
const payload = source || {};
|
|
const text = typeof payload.text === "string" ? payload.text.trim() : "";
|
|
|
|
if (!text) {
|
|
return {
|
|
error: "Missing required parameter: text",
|
|
};
|
|
}
|
|
|
|
return {
|
|
text,
|
|
width: parseIntWithBounds(payload.size, 512, 128, 2048),
|
|
margin: parseIntWithBounds(payload.margin, 2, 0, 10),
|
|
dark: typeof payload.dark === "string" && payload.dark ? payload.dark : "#000000",
|
|
light: typeof payload.light === "string" && payload.light ? payload.light : "#FFFFFF",
|
|
};
|
|
}
|
|
|
|
async function sendQrPng(source, res, next) {
|
|
const normalized = normalizePayload(source);
|
|
|
|
if (normalized.error) {
|
|
return res.status(400).json({ error: normalized.error });
|
|
}
|
|
|
|
try {
|
|
const image = await QRCode.toBuffer(normalized.text, {
|
|
type: "png",
|
|
width: normalized.width,
|
|
margin: normalized.margin,
|
|
color: {
|
|
dark: normalized.dark,
|
|
light: normalized.light,
|
|
},
|
|
});
|
|
|
|
res.setHeader("Content-Type", "image/png");
|
|
res.setHeader("Cache-Control", "no-store");
|
|
return res.send(image);
|
|
} catch (error) {
|
|
return next(error);
|
|
}
|
|
}
|
|
|
|
app.get("/", (_req, res) => {
|
|
res.json({
|
|
service: "qr-code-api",
|
|
usage: "GET /api/qr?text=hello or POST /api/qr with JSON body { text }",
|
|
});
|
|
});
|
|
|
|
app.get("/health", (_req, res) => {
|
|
res.json({ status: "ok" });
|
|
});
|
|
|
|
app.get("/api/qr", (req, res, next) => sendQrPng(req.query, res, next));
|
|
app.post("/api/qr", (req, res, next) => sendQrPng(req.body, res, next));
|
|
|
|
app.use((err, _req, res, _next) => {
|
|
console.error(err);
|
|
res.status(500).json({ error: "Failed to generate QR code" });
|
|
});
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`QR API listening on port ${PORT}`);
|
|
});
|