Step 4

As stated earlier, we will eventually use a database to add persistence to this application. For now, we will add a Data Access Object for Note.

In a nutshell, a Data Access Object is an object that provides an abstraction over some type of database or other persistence mechanism.

Create the NoteDao.js file inside the model folder with the following content:

class NoteDao {
  constructor() {
    this.notes = [];
  }
}

module.exports = NoteDao;

We shall provide methods for common database operations.

CRUD stands for create, read, update, and delete. It refers to the common tasks you want to carry out on database.

NoteDao is going to provide CRUD operation for notes.

Let's start with "create"; add the following method to NoteDao:

create(content, author) {
  this.notes.push(new Note(content, author));
}

To use Note, you must import it in NoteDao.js:

const Note = require("./Note.js");

Most databases will assign a unique ID to an object once it is created. We can simulate that here:

create(content, author) {
  const note = new Note(content, author);
  note._id = this.nextID();
  this.notes.push(note);
  return note;
}

where we declare nextID in the constructor

constructor() {
  this.notes = [];
  this.nextID = uniqueID();
}

Here is the implementation of uniqueID()

const uniqueID = function() {
  let id = 0;
  return function() {
    return id++;
  }
}

Notice the use of closure! Place uniqueID outside of the NoteDao class definition.