Now that we can store messages in the database, let's integrate this into the Notes router module.
In routes/notes.mjs, add this to the import statements:
import * as messages from '../models/messages-sequelize';
If you wish to implement a different data storage model for messages, you'll need to change this import statement. You should consider using an environment variable to specify the module name, as we've done elsewhere:
// Save incoming message to message pool, then broadcast it
router.post('/make-comment', ensureAuthenticated, async (req, res, next) => {
try {
await messages.postMessage(req.body.from,
req.body.namespace, req.body.message);
res.status(200).json({ });
} catch(err) {
res.status(500).end(err.stack);
}
});
// Delete the indicated message
router.post('/del-message', ensureAuthenticated, async (req, res, next) => {
try {
await messages.destroyMessage(req.body.id, req.body.namespace);
res.status(200).json({ });
} catch(err) {
res.status(500).end(err.stack);
}
});
This pair of routes, /notes/make-comment and /notes/del-message, is used to post a new comment or delete an existing one. Each calls the corresponding data model function and then sends an appropriate response back to the caller.
Remember that postMessage stores a message in the database, and then it turns around and emits that message to other browsers. Likewise, destroyMessage deletes the message from the database, then emits a message to other browsers saying that the message has been deleted. Finally, the results from recentMessages will reflect the current set of messages in the database.
Both of these will be called by AJAX code in the browser:
module.exports.socketio = function(io) {
io.of('/view').on('connection', function(socket) {
// 'cb' is a function sent from the browser, to which we
// send the messages for the named note.
socket.on('getnotemessages', (namespace, cb) => {
messages.recentMessages(namespace).then(cb)
.catch(err => console.error(err.stack));
});
});
messages.emitter.on('newmessage', newmsg => {
io.of('/view').emit('newmessage', newmsg);
});
messages.emitter.on('destroymessage', data => {
io.of('/view').emit('destroymessage', data);
});
..
};
This is the Socket.IO glue code, which we will add to the code we looked at earlier.
The getnotemessages message from the browser requests the list of messages for the given Note. This calls the recentMessages function in the model. This uses a feature of Socket.IO where the client can pass a callback function, and server-side Socket.IO code can invoke that callback, giving it some data.
We also listen to the newmessage and destroymessage messages emitted by the messages model, sending corresponding messages to the browser. These are sent using the method described earlier.