the problem is, I am not able to make a request to MongoDB after validating the request with the following code:
module.exports.validateRegisterInput = (
username,
email,
password,
confirmPassword
) => {
const errors = {};
if (username.trim() === "") {
errors.username = "Username must be provided";
}
if (email.trim() === "") {
errors.email = "Email must be provided";
} else {
const validEmail =
/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
if (!email.match(validEmail)) {
errors.email = "Email must be valid";
}
}
if (password === "") {
errors.password = "Password must be provided";
}
if (password !== confirmPassword) {
errors.password = "Passwords must match";
}
return {
errors,
vaild: Object.keys(errors).length < 1,
};
};
the validators work fine and check the request for any mistakes but once there is no issue with the request it does not let me send a request and raises an error anyway, also I am using the validators in the following way:
module.exports = {
Mutation: {
async register(
parent,
{ registerInput: { username, email, password, confirmPassword } }
) {
const { valid, errors } = validateRegisterInput(
username,
email,
password,
confirmPassword
);
if (!valid) {
throw new UserInputError("Errors", { errors });
}
...
so, I solved the problem, the problem was I was not calling the question directly and changed it to:
validateRegisterInput(username, email, password, confirmPassword);
and add errors in the validators and not in the index
const { UserInputError } = require("apollo-server");
module.exports.validateRegisterInput = (
username,
email,
password,
confirmPassword
) => {
if (username.trim() === "") {
throw new UserInputError("Username must be provided", {
errors: {
username: "Username must be provided",
},
});
}
if (email.trim() === "") {
throw new UserInputError("Email must be provided", {
errors: {
email: "Email must be provided",
},
});
} else {
const validEmail =
/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
if (!email.match(validEmail)) {
throw new UserInputError("Email must be correct", {
errors: {
email: "Email must be correct",
},
});
}
}
if (password === "") {
throw new UserInputError("Password must be provided", {
errors: {
password: "Password must be provided",
},
});
}
if (password !== confirmPassword) {
throw new UserInputError("Passwords must match", {
errors: {
password: "Password must match",
},
});
}
};