import type { ValidationArguments, ValidationOptions, ValidatorConstraintInterface } from 'class-validator'; import { ModuleRef } from '@nestjs/core'; /** * 验证上下文,传递给验证函数 */ export interface ValidationContext { /** 当前验证的值 */ value: any; /** 当前对象实例 */ object: any; /** 属性名 */ property: string; /** 约束参数(包含验证函数和额外参数) */ constraints: any[]; /** 类名 */ targetName: string; /** 所有验证参数(原始 ValidationArguments) */ args: ValidationArguments; } /** * 验证函数类型 * @param value 当前验证的值 * @param context 验证上下文 * @param extraArgs 额外参数(可选) * @returns boolean 或 Promise */ export type ValidatorFunction = (value: any, context: ValidationContext, ...extraArgs: any[]) => boolean | Promise; /** * 验证约束类型 * * 支持以下几种形式: * 1. 直接函数:(value, context) => boolean * 2. Entity 方法名:'methodName' * 3. Service + 方法名:[ServiceClass, 'methodName'] * 4. 延迟引用 Service:[() => ServiceClass, 'methodName'] * 5. 带额外参数:[ServiceClass, 'methodName', arg1, arg2, ...] */ export type ValidationConstraint = ValidatorFunction | string | [Function | (() => Function), string, ...any[]]; /** * 装饰器选项 */ export interface CustomValidateOptions extends ValidationOptions { /** 错误消息(支持字符串、函数、i18n key) */ message?: string | ((args: ValidationArguments) => string); /** 是否异步(可选,会自动检测) */ async?: boolean; } export declare class CustomValidateValidator implements ValidatorConstraintInterface { private readonly moduleRef; constructor(moduleRef: ModuleRef); /** * 验证入口 */ validate(value: any, args: ValidationArguments): Promise; /** * 调用内联函数 */ private callFunction; /** * 调用 Entity 方法 */ private callEntityMethod; /** * 调用 Service 方法 */ private callServiceMethod; /** * 默认错误消息 */ defaultMessage(args: ValidationArguments): string; } /** * @CustomValidate 装饰器 * * 支持多种验证方式的灵活验证装饰器 * * @example * * // 1. 内联函数(同步) * @CustomValidate( * (value) => value > 0, * { message: '价格必须大于0' } * ) * price: number; * * @example * // 2. 内联函数(异步) * @CustomValidate( * async (value, context) => { * const response = await fetch(`/api/check/${value}`); * return response.ok; * } * ) * username: string; * * @example * // 3. Entity 方法 * @CustomValidate('validateVersion') * version: string; * * validateVersion(value: string): boolean { * return /^\d+\.\d+\.\d+$/.test(value); * } * * @example * // 4. Service 方法 * @CustomValidate([UserValidationService, 'checkUsername']) * username: string; * * @example * // 5. 延迟引用(解决循环依赖) * @CustomValidate([() => UserValidationService, 'checkUsername']) * username: string; * * @example * // 6. 带额外参数 * @CustomValidate( * [ValidationService, 'checkRange', 0, 100], * { message: '价格必须在 0-100 之间' } * ) * price: number; * * @example * // 7. 使用 i18n * @CustomValidate( * (value) => value.length >= 6, * { message: 'validation.PASSWORD_TOO_SHORT' } * ) * password: string; * * @param constraint 验证约束(函数、方法名、或 [Service, 方法名]) * @param validationOptions 验证选项 */ export declare function CustomValidate(constraint: ValidationConstraint, validationOptions?: CustomValidateOptions): PropertyDecorator;