UNPKG

@opengis/fastify-table

Version:

core-plugins

66 lines (65 loc) 1.84 kB
import { toDataURL, toString } from "qrcode"; function isAllowedType(type) { return Boolean({ png: 1, svg: 1, // eps: 1, // not supported? // pdf: 1, // not supported? }[type]); } function isAllowedErrorCorrectionLevel(ecLevel) { return Boolean({ L: 1, M: 1, Q: 1, H: 1, }[ecLevel]); } export default async function qrcodeGenerator({ hash, }) { const text = String(hash?.text || ""); const type = String(hash?.type || "png").toLowerCase(); const ecLevel = String(hash?.ec_level || "M").toUpperCase(); const margin = Math.abs(hash?.margin || (type === "png" ? 4 : 1)); let size; if (type === "png") { size = Math.abs(hash?.size) || 5; } else if (type === "svg") { size = Math.abs(hash?.size) || undefined; } if (!text) { return "Qr text is required."; } if (!isAllowedType(type)) { return `Type "${type}" is not allowed.`; } if (!isAllowedErrorCorrectionLevel(ecLevel)) { return `Error correction level "${ecLevel}" is not allowed.`; } try { if (type === "svg") { // для SVG нужен toString return await toString(text, { type: "svg", errorCorrectionLevel: ecLevel, margin, width: size, }); } // для PNG/JPEG/WebP — toDataURL const mime = type === "png" ? "image/png" : type === "jpg" || type === "jpeg" ? "image/jpeg" : "image/webp"; return await toDataURL(text, { errorCorrectionLevel: ecLevel, type: mime, margin, width: size, }); } catch (err) { return err.toString(); } }