@opengis/fastify-table
Version:
core-plugins
67 lines (58 loc) • 2.09 kB
JavaScript
import qr from 'qrcode';
function isAllowedType(type) {
return Boolean({
png: 1, svg: 1, eps: 1, pdf: 1,
}[type]);
}
function isAllowedErrorCorrectionLevel(ecLevel) {
return Boolean({
L: 1, M: 1, Q: 1, H: 1,
}[ecLevel]);
}
/**
* Генерує зображення з QR кодом, що перенаправляє на посилання.
*
* @summary Генератор QR код. Є можливість задання відступу та встановлення розширення вихідного зображення
* @priority 3
* @type helper
* @tag file
* @alias qrcode-generator-base64
* @example
* {{{qrcode-generator-base64 text=@root.req.domain type='png' margin=1}}}
* @param {String} text Змінна, що містить посилання на файл або сторінку
* @param {String} type Розширення зображення
* @param {String} ec_level (?)
* @param {Number} margin Відступ
* @param {Number} size Розмір
* @returns {String} Returns HTML
*/
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.`;
}
const options = (type === 'png' || type === 'svg') ? {
ec_level: ecLevel, type, margin, size,
} : { ec_level: ecLevel, type, margin };
try {
const qrString = await qr.toDataURL(text, options);
return qrString;
} catch (err) {
return err.toString();
}
};