- Integrated dotenv for environment variable management. - Updated queueWorker to use WORKER_INTERVAL from .env or default to 5 seconds. - Added a new bulk SMS endpoint to queue multiple messages in a single request, with validation and transaction handling. - Updated package.json and package-lock.json to include dotenv dependency.
92 lines
2.9 KiB
JavaScript
92 lines
2.9 KiB
JavaScript
const express = require('express');
|
|
const db = require('../db');
|
|
|
|
module.exports = function (io) {
|
|
const router = express.Router();
|
|
|
|
// Existing endpoint (kept for compatibility if needed, or can be removed later)
|
|
router.post('/data', (req, res) => {
|
|
const { phone, code } = req.body;
|
|
|
|
if (!phone || !code) {
|
|
return res.status(400).json({ error: 'Phone and Code are required.' });
|
|
}
|
|
|
|
console.log('Received data at /api/data:', { phone, code });
|
|
|
|
io.emit('sendSignInData', { phone, code });
|
|
|
|
return res.status(200).json({
|
|
message: 'Data received and processed successfully.',
|
|
received: { phone, code }
|
|
});
|
|
});
|
|
|
|
// New endpoint to queue SMS
|
|
router.post('/sms', (req, res) => {
|
|
const { phone, message } = req.body;
|
|
|
|
if (!phone || !message) {
|
|
return res.status(400).json({ error: 'Phone and message are required.' });
|
|
}
|
|
|
|
// Insert into queue
|
|
db.run(`INSERT INTO sms_queue (phone, message) VALUES (?, ?)`, [phone, message], function(err) {
|
|
if (err) {
|
|
console.error('Error inserting into sms_queue:', err);
|
|
return res.status(500).json({ error: 'Failed to queue SMS.' });
|
|
}
|
|
|
|
return res.status(202).json({
|
|
message: 'SMS queued successfully.',
|
|
id: this.lastID
|
|
});
|
|
});
|
|
});
|
|
|
|
// Bulk endpoint to queue multiple SMS
|
|
router.post('/sms/bulk', (req, res) => {
|
|
const { messages } = req.body;
|
|
|
|
if (!Array.isArray(messages) || messages.length === 0) {
|
|
return res.status(400).json({ error: 'messages array is required and cannot be empty.' });
|
|
}
|
|
|
|
// Validate all messages first
|
|
for (const msg of messages) {
|
|
if (!msg.phone || !msg.message) {
|
|
return res.status(400).json({ error: 'Each message must have a phone and message.' });
|
|
}
|
|
}
|
|
|
|
db.serialize(() => {
|
|
db.run("BEGIN TRANSACTION");
|
|
const stmt = db.prepare("INSERT INTO sms_queue (phone, message) VALUES (?, ?)");
|
|
|
|
for (const msg of messages) {
|
|
stmt.run([msg.phone, msg.message], function(err) {
|
|
if (err) {
|
|
console.error('Error inserting into sms_queue during bulk operation:', err);
|
|
}
|
|
});
|
|
}
|
|
|
|
stmt.finalize();
|
|
|
|
db.run("COMMIT", (err) => {
|
|
if (err) {
|
|
console.error('Error committing bulk SMS transaction:', err);
|
|
return res.status(500).json({ error: 'Failed to queue bulk SMS.' });
|
|
}
|
|
|
|
return res.status(202).json({
|
|
message: `Successfully queued ${messages.length} SMS messages.`
|
|
});
|
|
});
|
|
});
|
|
});
|
|
|
|
return router;
|
|
};
|
|
|