router_message_triggerBlastMedia.js
const db = require("../../db/db");
const format = require("date-format");
const datetb = format("yyMM", new Date());
const axios = require("axios");
const axiosRetry = require('axios-retry');
const { KeiLog } = require('../../lib/Logger');
/**
* Sets up an Express route to trigger a blast of template media messages.
*
* This function adds a GET route to the provided Express application. When accessed,
* it retrieves template parameters, constructs URLs for message sending, and then
* sends messages using axios requests. It also handles updating database flags
* based on the success or failure of these requests.
*
*@module trigerBlastTemplateMedia
* @param {Object} app - The Express application instance.
*/
module.exports = async function (app) {
app.get("/trigerBlastTemplateMedia", async (req, res) => {
try {
axiosRetry(axios, { retries: 3 });
const datas = await db.getParameterTemplate();
//Making Requests to Sendtemplate API through Promise.all()
const requests = []
for (let i = 0; i < datas.length; i++) {
const item = datas[i];
let url = `http://localhost:8001/sendtemplateMedia?number=${item.nomor}&template=${item.template_pesan}&attachment=${item.media}`;
const result = (await axios.get(`http://localhost:8001/list_template?name_template=${item.template_pesan}`)).data[0];
const params = result.components?.[1]?.text?.match(/\{\{(\d+)}}/g);
if (params) {
const formattedParams = params.map((param) => `param${param.slice(2).replace(/}}/g, "")}`);
const [select] = await db.custom(`select ${formattedParams.join(', ')} from tb_nomor_${datetb} where flag=1`);
const values = Object.values(select?.[i] ?? {}).filter(v => v != null);;
if (values.length > 0) {
url += `¶meter=${values.join(',')}`;
}
}
requests.push(axios.get(url)
.then(async function(response) {
console.log(response.data);
await db.custom(`UPDATE tb_nomor_${datetb} SET flag = 2 where nomor = ${item.nomor}`);
})
.catch(async function(err) {
console.log(err);
await db.custom(`UPDATE tb_nomor_${datetb} SET flag = 10 where nomor = ${item.nomor}`);
})
);
}
await Promise.all(requests);
res.send("Data processed");
} catch (error) {
console.log(error);
res.status(500).send("Internal server error");
}
});
};