The Notes model now sends events as Notes are created, updated, or destroyed. For this to be useful, the events must be displayed to our users. Making the events visible to our users means the controller and view portions of the application must consume those events.
Let's start making changes to routes/index.mjs:
router.get('/', async (req, res, next) => {
try {
let notelist = await getKeyTitlesList();
res.render('index', {
title: 'Notes', notelist: notelist,
user: req.user ? req.user : undefined
});
} catch (e) { next(e); }
});
We need to reuse part of the original routing function, to use it in another function. Therefore, we've pulled code that used to be in this block into a new function, getKeyTitlesList:
async function getKeyTitlesList() {
const keylist = await notes.keylist();
var keyPromises = keylist.map(key => {
return notes.read(key).then(note => {
return { key: note.key, title: note.title };
});
});
return Promise.all(keyPromises);
};
This portion of the original routing function is now its own function. It generates an array of items containing the key and title for all existing Notes, using Promise.all to manage the process of reading everything.
export function socketio(io) {
var emitNoteTitles = async () => {
const notelist = await getKeyTitlesList()
io.of('/home').emit('notetitles', { notelist });
};
notes.events.on('notecreated', emitNoteTitles);
notes.events.on('noteupdate', emitNoteTitles);
notes.events.on('notedestroy', emitNoteTitles);
};
Here is the socketio function we discussed while modifying app.mjs. We receive the io object, then use it to emit a notestitles event to all connected browsers.
The io.of('/namespace') method restricts whatever follows to the given namespace. In this case, we're emitting a notestitle message to the /home namespace.
The code, in this case, is fairly straightforward. It listens to the events we just implemented, notecreated, noteupdate, and notedestroy. For each of these events, it emits an event, notetitles, containing the list of note keys and titles.
That's it!
As Notes are created, updated, and destroyed, we ensure that the homepage will be refreshed to match. The homepage template, views/index.hbs, will require code to receive that event and rewrite the page to match.