Please someone help me! I've tried many anwsers i found on stackoverflow, but none of they worked for me. I'm trying to call dynamic function inside a forEach, which inside that function also has a async/await which is already working (the one returning the collection). Here is my code.
export default function validatorJS(data: any, validations: any) {
let error: any = {};
const message = {
unique: `The value [{var}] already exists.`,
};
let methods: any = {
unique: async (_field: any, _validations: any) => {
// This is returning a collection of a Model.
const res = await _validations.unique.find({ [_field]: data[_field] });
if (res.length > 0) {
error = {
...error,
[_field]: [...(error[_field] || []), message.unique.replace("{var}", data[_field])],
};
}
},
};
function validate() {
Object.keys(validations).forEach((field: any) => {
Object.keys(validations[field]).forEach(async (method: any) => {
if (method in methods) await methods[method](field, validations[field]);
});
});
// Getting here before the methods.unique finishs
return Object.keys(error).length > 0 ? error : false;
}
return validate();
}