So I’m pretty stumped by this, I must be missing a design pattern or something obvious when creating modules.
I create a socket in my app.js file like so:
// app.js
sequelize.sync()
.then(result => {
const server = app.listen(8080);
const io = require('./util/socket').init(server);
io.on('connection', socket => {
socket.on('chatbox', (data) => {
twilio.sendSMS(data); // Although this works for sending
// msgs, this isn't (?) the way to handle 2 way comms.
// I probably need to require the twilio module here
// and pass the socket as a parameter
});
});
})
This allows me to create a socket connection to any frontend that connects, and send an sms when they type in a chat box. That part works great, but the way I’m structuring seems wrong.
The problem is that I need access to this specific socket instance in the twilio module so that I can send the SMS reply back to the frontend in the handleReply
function:
// twillio.js
exports.sendSMS = (msg) => {
client.messages.create({
to: process.env.MY_PHONE_NUMBER,
from: process.env.TWILIO_PHONE_NUMBER,
body: msg
})
.then(message => console.log(message.sid));
}
exports.handleReply = (req, res, next) => {
const twiml = new MessagingResponse();
twiml.message(`You said ${req.body.Body}`);
// ***I'd like to reply using the socket here***
res.setHeader('Content-Type', 'text/xml');
res.status(200).send(twiml.toString());
};
But how can I pass the socket to the twilio module?
Any help would be amazing
Thanks,
Nick