I'm trying to build a certificate generation module using nodeJS.
The api to create certificate is as follows
// Create certificate
const express = require('express');
const router = express.Router();
const { createCanvas } = require('canvas')
const fs = require("fs");
const { decodeBase64Image } = require('../helper/certificatehelper');
router.post('/imageadd', async (req, res, next) => {
try {
const { name } = req.body;
const width = 1920
const height = 1080
const canvas = createCanvas(width, height)
const context = canvas.getContext('2d')
context.fillStyle = "white";
context.fillRect(0, 0, width, height)
context.fillStyle = '#000'
context.font = "72px Arial";
context.textAlign = "center";
context.fillText(name, 900, 500);
const dataurl = canvas.toDataURL();
const decodedImg = decodeBase64Image(dataurl);
const imageBuffer = decodedImg.data;
fs.writeFileSync(`./src/images/image1.png`, imageBuffer);
fs.readFile('./src/images/image1.png', function(err, data) {
if (err) throw err; // Fail if the file can't be read.
res.writeHead(200, {'Content-Type': 'image/jpeg'});
res.end(data); // Send the file data to the browser.
});
res.json({ data: respArray, success: true, msg: 'Certificate generated' });
} catch (error) {
res.json({ success: false, msg: error.message });
}
})
module.exports = router;
The problem I'm facing is, If multiple request are send in parallel how do I generate one certificate at a time (synchronized).
Other requests need to wait till the certificate is generated for previous request.
The certificates should be generated in a separate process from the main app process.
How do I solve the above given problem.