-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathqrcode-generator.js
More file actions
72 lines (65 loc) · 2.15 KB
/
qrcode-generator.js
File metadata and controls
72 lines (65 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const { QRCodeCanvas } = require('@loskir/styled-qr-code-node'); // or CommonJS
const cloudinary = require('cloudinary').v2;
const dotenv = require('dotenv');
const fs = require('fs');
const generateData = require('./canvasData');
const folderName = 'QrCode';
dotenv.config()
cloudinary.config({
secure: true,
cloud_name: process.env.CLOUDE_NAME,
api_key: process.env.CLOUD_API_KEY,
api_secret: process.env.CLOUD_API_SECRET,
});
const uploadImage = async (imagePath) => {
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
const subFolderName = `${year}-${month}-${day}`;
const expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 3)
const options = {
use_filename: true,
unique_filename: false,
overwrite: true,
folder: folderName + '/' + subFolderName,
expires_at: expirationDate
};
try {
const result = await cloudinary.uploader.upload(imagePath, options);
return result;
} catch (error) {
console.error(error);
}
};
function clearTempFile(filePath) {
setTimeout(() => {
fs.unlink(filePath, (err) => {
if (err) {
console.error(err);
}
});
}, 60000);
}
async function generateQrCode(data = {}, isUpload = false) {
const downloadOptions = data.downloadOptions || {}
const canvas = generateData(data)
const qrCode = new QRCodeCanvas(canvas);
const currentDate = new Date();
if (!fs.existsSync(`./temp`)) {
fs.mkdirSync(`./temp`, { recursive: true });
}
const outputFileName = `./temp/qrcode_generated_${currentDate.getTime()}.${downloadOptions.extension || 'png'}`;;
await qrCode.toFile(outputFileName, downloadOptions.extension || 'png');
clearTempFile(outputFileName);
if (isUpload) {
const uploadResult = await uploadImage(outputFileName)
return uploadResult;
} else {
return {
url: outputFileName
};
}
}
module.exports = generateQrCode;