Struggling with finding a solution for this unique kind of "array validation" I'm attempting.
My goal is to validate dynamic sets of rest parameters from function arguments against a REST api schema. Here's an example:
@Validation(Schema.update)
public async update(id: string, model: Model) => { }
The idea is to use a decorator to intercept the function call and perform validation based on the provided schema:
export function Validation(schema: ObjectSchema) {
return (target: any, propName: string | symbol, descriptor: PropertyDescriptor): void => {
const originalMethod = descriptor.value!;
descriptor.value = function (...rest: any[]): ApiResult {
const { error } = schema.validate({ ...rest });
if (error) {
console.error(error.message);
return new ErrorApiResult({ statusCode: 400, message: error?.message });
}
return originalMethod.apply(this, arguments);
};
};
}
Although it currently functions well, there's one issue - defining the validation schema like below:
export const Schema = {
update: Joi.object({
0: Joi.string(),
1: ModelSchema,
}),
}
The main concern is that Joi generates validation error messages that label fields as 0.user.name
instead of model.user.name
, causing confusion.
I would prefer to define the endpoint schema like this:
export const Schema = {
update: Joi.object({
id: Joi.string().required(),
model: ModelSchema,
}),
}
However, I haven't figured out how to achieve this yet. Even exploring Joi.array(), it seems more suited for handling collections of objects rather than strict argument arrays.
EDIT:
I attempted using the .label()
method to adjust the error message labels, but faced challenges when dealing with nested keys. While it works for simple validations like the id
argument, it fails to display correctly when validating properties within ModelSchema
, showing "1.user.name"
in error messages.