Hello hello this is my recursive function which do validation for nested properties. So i am trying to return array with all errors from this function. Clearly i am doing something wrong since there are many loops. Please help me to return array of objects.
export async function validateIt<T>(payload: T, validations: IValidation<T>[], errors = []) {
return await Promise.all(
validations.map(async x => {
return await Promise.all(x.validators?.map(async validator => {
if (!x.nestedValidations) {
const results = await validate(validator, payload, x.field)
errors.push(results)
return errors
} else {
await Promise.all(
payload[x.field].map(async (nestedPayloadItem) => {
await validateIt(nestedPayloadItem, x.nestedValidations)
})
)
}
}))
}
)
)
}
this is how payload looks
{
"event": 103,
"itemCode": "Test",
"storeProductAvailabilityList": [
{"startTime": 200, "endTime": 100, "pricingType": "SELLD"},
{"type": "REG", "endTime": 100}
],
"storeProductImageList": [
{"type": "ONSITE", "base64": "3123123123"},
{"type": "CHART"}
]
}
And here is function call
const errors = await validateIt<PostStoreProductPayload>(
payload,
[{
field: "eventId",
validators: [{
type: 'required'
}]
},{
field: "name",
validators: [{
type: 'required'
}]
},{
field: "storeProductImageList",
validators: [{
type: 'required'
}],
nestedValidations: [{ field: 'base64', validators: [{ type: 'required'}]}, { field: 'type', validators: [{ type: 'enum', values: ['CHART', 'CART']}]} ]
},
{
field: "sku",
validators: [{
type: 'required'
}]
}]
)
Getting multidimensional array so my question is this right way to write recursion? Am i doing right return from this part
if (!x.nestedValidations) {
const results = await validate(validator, payload, x.field)
errors.push(results)
return errors
}
I am slightly confused all these "async".
Looking for this result.
[
{ name: 'required' },
{ sku: 'required' },
]