vasansr / pro-mern-stack

Code Listing for the book Pro MERN Stack
http://www.apress.com/in/book/9781484226520
343 stars 159 forks source link

Page 86 error in listing 5-7 #28

Closed MurdrOfCrows closed 7 years ago

MurdrOfCrows commented 7 years ago

The first line of the validateIssue function for (const field in issueFieldType) { should surely be for (const field in issue) { since otherwise you are just iterating over the fields of the global 'schema' object rather than the issue object. Thus, as it stands, no invalid fields in the issue object will ever be removed.

However, by making this change, the function will now fail to ensure that all required fields are included in the received issue object if a required field is entirely absent from the posted issue object. Thus you actually need two loops, one that iterates over the issue object to check for and prune any unwanted fields and another to iterate over the 'schema' object to check that the issue object contains all the required fields. Something along the lines of:-

function validateIssue(issue) {
  // Check for and prune any non-schema fields
  // from the issue object.
  for (const field in issue) {
    if (!issueFieldType[field]) {
      delete issue[field];
    }
  }
  // Check that all required fields are present
  // in the issue object.
  for (const field in issueFieldType) {
    const type = issueFieldType[field];
    if (type === 'required' && !issue[field]) {
      return `${field} is required`;
    }
  }

  if (!validIssueStatus[issue.status]) {
    return `${issue.status} is not a valid status`;
  }

  return null;
}

(My inclination now would be to break this out into three functions)

MurdrOfCrows commented 7 years ago

I see that this bug is picked up on later in the book (page 144). I shall therefore close this issue.