Step 4
Let us implement the operations of NoteDao
. Notice the functions are decorated with the aync
keyword. It is typical to perform CRUD operations asynchronously.
Implement create
operation as follows:
// Pre: title and text are not undefined, and title is not empty
async create({ title, text }) {
const note = new Note(title, text);
this.notes.push(note);
return note;
}
Note the pre-condition statement. We will deal with error handling later!
Implement update
operation as follows:
// Pre: id is a valid note ID
async update(id, { title, text }) {
const index = this.notes.findIndex((note) => note._id === id);
if (title !== undefined) {
this.notes[index].title = title;
}
if (text !== undefined) {
this.notes[index].text = text;
}
return this.notes[index];
}
Implement delete
operation as follows:
// Pre: id is a valid note ID
async delete(id) {
const index = this.notes.findIndex((note) => note._id === id);
const note = this.notes[index];
this.notes.splice(index, 1);
return note;
}
Implement read
operation as follows:
// Pre: id is a valid note ID
async read(id) {
return this.notes.find((note) => note._id === id);
}
Implement readAll
operation as follows:
async readAll(query = "") {
if (query !== "") {
return this.notes.filter(
(note) => note.title.includes(query) || note.text.includes(query)
);
}
return this.notes;
}
Notice the readAll
takes in an optional query
parameter to facilitate searching among the notes.
Save and commit the changes.