Performance: Custom validation decorators
MEDIUM IMPACT
This affects the runtime validation speed during request processing and can impact server response time and user experience.
import { registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator'; @ValidatorConstraint({ async: true }) export class IsUniqueEmailConstraint implements ValidatorConstraintInterface { private cache = new Set<string>(); async validate(email: string) { if (this.cache.has(email)) return true; // Cached result // Simulate fast async check const isUnique = email !== 'taken@example.com'; if (isUnique) this.cache.add(email); return isUnique; } } export function IsUniqueEmail(validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ target: object.constructor, propertyName: propertyName, options: validationOptions, constraints: [], validator: IsUniqueEmailConstraint, async: true }); }; }
import { registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator'; @ValidatorConstraint({ async: true }) export class IsUniqueEmailConstraint implements ValidatorConstraintInterface { validate(email: string) { return new Promise(resolve => { setTimeout(() => { resolve(email !== 'taken@example.com'); }, 1000); // Simulates slow async check }); } } export function IsUniqueEmail(validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ target: object.constructor, propertyName: propertyName, options: validationOptions, constraints: [], validator: IsUniqueEmailConstraint, async: true }); }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Slow async validation with delay | N/A (server-side) | N/A | N/A | [X] Bad |
| Cached fast validation logic | N/A (server-side) | N/A | N/A | [OK] Good |