Answer the question
In order to leave comments, you need to log in
How to use Promise in a loop?
Hello!
I am writing my input validator in JavaScript, the problem is that everything inside is on cycles, checks, etc. So in general everything works. But when I try to check some value in the database for uniqueness inside the cycles, it does not wait for the result and pretends that there is no error and creates a user in the database. I am not a guru, I am learning, I will be grateful for the answer. Prompt that the logic remains approximately the same. Thank you!
Here is an example code:
const request = {
name: "Абдулсалам",
age: 21,
email: "[email protected]"
}
const rules = {
name: "required|string",
age: "required|number|min:18",
email: "required|email|unique:users"
}
const Validator = require("../Classes/Validator");
const validator = new Validator(request, rules);
if (validator.fails()) {
const response = {
message: "Bad Request",
success: false,
status: 400,
data: { errors: validator.errors },
};
return res.status(response.status).json(response);
}
const { QueryTypes } = require("sequelize");
const { sequelize } = require("../../models/index");
class Validator {
constructor(request, rules) {
this.request = request;
this.rawRules = rules;
}
errors = [];
currentKey = null;
set addError(message) {
this.errors.push({ [this.currentKey]: message });
}
get rules() {
const rules = [];
for (const key in this.rawRules) {
rules.push({ [key]: this.rawRules[key].split("|") });
}
return rules;
}
fails() {
this.rules.forEach((objRules) => {
for (const key in objRules) {
const rules = objRules[key];
const request = this.request[key];
this.currentKey = key;
// EXISTS
if (rules.includes("exists") && !request) return;
// REQUIRED
if (
rules.includes("required") &&
(request === "" || request === null || request === undefined)
)
return (this.addError = "Required field");
// STRING
if (rules.includes("string") && typeof request !== "string")
return (this.addError = "This field must be a string");
// NUMBER
if (rules.includes("number") && typeof request !== "number")
return (this.addError = "This field must be a number");
// EMAIL
if (
rules.includes("email") &&
!request.match(
/^(([^<>()\[\]\.,;:\[email protected]\"]+(\.[^<>()\[\]\.,;:\[email protected]\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\[email protected]\"]+\.)+[^<>()[\]\.,;:\[email protected]\"]{2,})$/i
)
)
return (this.addError = "Invalid email");
// ":"
rules.forEach(async (rule) => {
if (rule.includes(":")) {
const [ruleKey, ruleValue] = rule.split(":");
const findRuleKey = (key) => ruleKey.includes(key);
// "-"
if (ruleValue.includes("-")) {
const [ruleValueLeft, ruleValueRight] = ruleValue.split("-");
// BETWEEN MIN-MAX
if (findRuleKey("between")) {
// BETWEEN MIN
if (
!(
(typeof request === "string" ? request.length : request) >=
ruleValueLeft
)
)
return (this.addError = `Minimum ${
typeof request === "string" ? "length" : "number"
}: ${ruleValueLeft}`);
// BETWEEN MAX
if (
!(
(typeof request === "string" ? request.length : request) <=
ruleValueRight
)
)
return (this.addError = `Maximum ${
typeof request === "string" ? "length" : "number"
}: ${ruleValueRight}`);
}
}
// MIN
if (
findRuleKey("min") &&
!(
(typeof request === "string" ? request.length : request) >=
ruleValue
)
)
return (this.addError = `Minimum ${
typeof request === "string" ? "length" : "number"
}: ${ruleValue}`);
// MAX
if (
findRuleKey("max") &&
!(
(typeof request === "string" ? request.length : request) <=
ruleValue
)
)
return (this.addError = `Maximum ${
typeof request === "string" ? "length" : "number"
}: ${ruleValue}`);
// AS
if (findRuleKey("as") && request !== this.request[ruleValue])
return (this.addError = `The value of the field "${this.currentKey}" does not match the value of the field "${ruleValue}"`);
// NOT
if (
findRuleKey("not") && typeof request === "string"
? request.toLowerCase() === ruleValue
: request === +ruleValue
)
return (this.addError = `Field "${this.currentKey}" cannot contain the value "${ruleValue}"`);
// LENGTH
if (
findRuleKey("length") &&
typeof request === "string" &&
request.length !== +ruleValue
)
return (this.addError = `The string length should be: ${ruleValue}`);
// UNIQUE
if (findRuleKey("unique")) {
const result = await sequelize.query(
`SELECT * FROM ${ruleValue} WHERE ${this.currentKey} = "${request}"`,
{ type: QueryTypes.SELECT }
);
if (!!result[0])
return (this.addError = `SELECT * FROM ${ruleValue} WHERE ${this.currentKey} = "${request}"`);
}
}
});
}
});
return !!this.errors.length;
}
}
module.exports = Validator;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question