As i said it's simple to the core
Compares the validation object with model and returns its invalid / does not exist.
async function validator(requestObject, validatingObj){
let paramsError = {
missingParams: [],
invalidParams: [],
message: ''
}
function constructMessage(_paramsError){
let missingParamsMsg = `Missing the following parameters ${_paramsError.missingParams.join()}`;
let invalidParamsMsg = `The Following parameters are invalid ${_paramsError.invalidParams.join()}`;
return missingParamsMsg + '. ' + invalidParamsMsg;
}
await Object.keys(validatingObj).map(validParam => {
Object.keys(requestObject).includes(validParam)
? typeof validatingObj[validParam] === typeof requestObject[validParam] ?
'' : paramsError.invalidParams.push(validParam) : paramsError.missingParams.push(validParam);
})
paramsError.message = constructMessage(paramsError);
return paramsError;
}
Now let's see an example on how to use it.
let requestObject = { username: 'one', mailid: 123123, rides: [] };
let validatingObj = {
username: "",
mobile: 0,
mailid: "",
age: 0,
rides: { driverid: 0, carModel: '' }
}
//validating object with the request object
validator(requestObject, validatingObj).then(paramsError => {
console.info('paramsError',paramsError);
}).catch(err => {
console.error("\nError",err)
})
Top comments (3)
I like the idea! But whatโs the use case for async/await?
And because Iโm quite opinionated, Iโd get the array of keys requestObject before iterating over validatingObj, instead of recomputing it in every iteration.
Nonetheless, thank you for sharing!
It's the opinions that enhances an idea.
As I was doing a map the output was undefined. Later I tried async way got the expected value.
PS It needs a little improvisation in terms of validating objects! ๐