0

would like to know if it is possible to validate a field based on the datatype of another field? My requirement is like this:

payload:

{
fieldName: "firstName",
filter: "CONTAINS",
value: "axe"
}

I need to create a custom decorator/validator to know if firstName can be filtered using CONTAINS. CONTAINS is only used for string type fieldNames. If the payload is like this,

{
fieldName: "createdAt",
filter: "BETWEEN",
value: [2022-01-01, 2022-12-31]
}

createdAt has a Date data type so it should be only be compatible with BETWEEN.

I have two possible ways of doing this:

A. I need a way to import/inject the entity file that contains firstName and createdAt to my custom decorator file so that I can check if their data types are compatible with the payload.filter that was passed to me.

Here is my createParamDecorator so far:

export const validateListUsers = async (
  _data: unknown,
  context: ExecutionContext,
) => {
   const payload: any = context.switchToRpc().getData();
   return payload;
};

export const ListRequestDTO = createParamDecorator(validateListUsers);

Or

B. Create a custom validator, and use it in the DTO file. I just don't know how to know the datatype of the DTO field that it is used in.

Here is my custom validator:

export function Filterable(property: string[], options?: ValidationOptions) {
return (object: any, propertyName: string) => {
    console.log(object.constructor.propertyName);
    console.log(propertyName);
    registerDecorator({
        target: object.constructor,
        propertyName,
        options,
        validator: {
            async validate(
                value: any,
                validationArguments?: ValidationArguments,
            ): Promise<boolean> {
                console.log('VALUE:', value);
                console.log(validationArguments);
                throw new Error('Method not implemented.');
            },
            defaultMessage(validationArguments?: ValidationArguments): string {
                console.log(validationArguments);
                throw new Error('Method not implemented.');
            },
        },
        async: true,
    });
};
}

Here is the usage:

export class UserDTO {
@IsString()
@Filterable(['CONTAINS', 'EQUALS'])
firstName: string;

@IsISO8601()
@Filterable(['BETWEEN'])
createdAt: string;
}

Is there a way to pass the datatype of firstName and createdAt in the custom validator? I was able to get firstName using the propertyName.

astra.xvi
  • 43
  • 7

0 Answers0