{"size": 1151, "ext": "js", "max_stars_repo_path": "server/validation/survey-answers-val.js", "max_stars_repo_name": "marwajomaa/connect5", "max_stars_repo_stars_event_min_datetime": "2018-12-23T23:32:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-23T23:32:03.000Z", "max_issues_repo_path": "server/validation/survey-answers-val.js", "max_issues_repo_name": "marwajomaa/connect5", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/validation/survey-answers-val.js", "max_forks_repo_name": "marwajomaa/connect5", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.8529411765, "max_line_length": 120, "alphanum_fraction": 0.6924413553}
const isEmpty = require("./is-empty");
const Questions = require("../database/models/Question");

const validateSurveyInput = async (data) => {
  // set up error obj to store errors
  const errors = {};

  // query the Question model using data.surveyType to get a list of the question ids for that survey which are required
  const questions = await Questions.find({ surveyType: data.surveyType, isRequired: true });
  // create array of question ids required
  const questionIDList = questions.map(e => e._id.toString());
  // create array of question ids for answers submitted
  const answers = Object.keys(data.formState);

  if (isEmpty(answers)) {
    questionIDList.forEach(e => (errors[e] = "this question must be answered"));
  } else {
    questionIDList.filter((e) => {
      if (!answers.includes(e)) {
        errors[e] = "this question must be answered";
      }
    });
  }

  // filter questionIdArray to find unanswered questions and put them into error obj

  console.log("ERRORS VALIDATE", errors);
  console.log("ISEMPTY", isEmpty(errors));

  return { errors, isValid: isEmpty(errors) };
};

module.exports = validateSurveyInput;
