Step 6

Import ApiError in NoteDao.js:

const ApiError = require("../model/ApiError");

Modify NoteDao.create operation as follows:

async create({ title, text }) {
  if (title === undefined || title === "") {
    throw new ApiError(400, "Every note must have a none-empty title!");
  }

  if (text === undefined) {
    throw new ApiError(400, "Every note must have a text attribute!");
  }

  const note = new Note(title, text);
  this.notes.push(note);
  return note;
}

Note I have now removed the pre-condition statement. The error code $400$ is a status code for the HTTP "bad request" error.

Modify NoteDao.update operation as follows:

async update(id, { title, text }) {
  const index = this.notes.findIndex((note) => note._id === id);

  if (index === -1) {
    throw new ApiError(404, "There is no note with the given ID!");
  }

  if (title !== undefined) {
    this.notes[index].title = title;
  }

  if (text !== undefined) {
    this.notes[index].text = text;
  }

  return this.notes[index];
}

The error code $404$ is a status code for the HTTP "resource not found" error.

Modify NoteDao.delete operation as follows:

async delete(id) {
  const index = this.notes.findIndex((note) => note._id === id);

  if (index === -1) {
    throw new ApiError(404, "There is no note with the given ID!");
  }

  const note = this.notes[index];
  this.notes.splice(index, 1);
  return note;
}

We will leave the NoteDao.read and NoteDao.readAll operations as they are. It is common in API design to return an empty array of resources when the "read" operations did not find any resource matching the request.

// returns an empty array if there is no note with the given ID
async read(id) {
  return this.notes.find((note) => note._id === id);
}

// returns an empty array if there is no note in the database 
//  or no note matches the search query
async readAll(query = "") {
  if (query !== "") {
    return this.notes.filter(
      (note) => note.title.includes(query) || note.text.includes(query)
    );
  }
  return this.notes;
}

Save and commit the changes.