Create a file named notes-memory.js in the models directory, with this code:
const Note = require('./Note');
var notes = [];
exports.update = exports.create = async function(key, title, body) {
notes[key] = new Note(key, title, body);
return notes[key];
};
exports.read = async function(key) {
if (notes[key]) return notes[key];
else throw new Error(`Note ${key} does not exist`);
};
exports.destroy = async function(key) {
if (notes[key]) {
delete notes[key];
} else throw new Error(`Note ${key} does not exist`);
};
exports.keylist = async function() { return Object.keys(notes); };
exports.count = async function() { return notes.length; };
exports.close = async function() { }
This is a simple in-memory data store that's fairly self-explanatory. The key for each Note instance is used as the index to an array, which in turn holds the Note instance. Simple, fast, and easy to implement. It does not support any long-term data persistence. Any data stored in this model will disappear when the server is killed.
We have used async functions because in the future we'll be storing data in the file system or in databases. Therefore, we need an asynchronous API.
The create and update functions are being handled by the same function. At this stage of the Notes application, the code for both these functions can be exactly the same because they perform the exact same operation. Later, when we add database support to Notes, the create and update functions will need to be different. For example, in a SQL data model, create would be implemented with an INSERT INTO command, while update would be implemented with an UPDATE command.