I'm currently developing a NestJS API using apollo-server-express and have created an InputType for appointments as shown below:
@InputType()
export class AppointmentInput {
@Field(of => String)
@IsNotEmpty()
name: string;
@Field(of => String)
@IsNotEmpty()
@IsDateString()
dateStart: string;
@Field(of => String)
@IsNotEmpty()
@IsDateString()
dateEnd: string;
@Field(of => Boolean)
@IsBoolean()
paid: boolean;
@Field(of => Int)
idDoctor: number;
@Field(of => Int)
idPatient: number;
@Field(of => Int)
idService: number;
}
If I want to validate if the name contains the letter 'a' using a Pipe, I can create a custom pipe like this:
import { PipeTransform, Injectable, ArgumentMetadata, HttpException, HttpStatus } from '@nestjs/common';
@Injectable()
export class NamePipe implements PipeTransform<string, string>{
transform(name: string, metadata: ArgumentMetadata) {
if (name.includes('a')) {
throw new HttpException('The name contains the letter "a"', HttpStatus.BAD_REQUEST);
}
return name;
}
}
However, when I try to use this pipe as a decorator along with validation decorators, I encounter the following error:
The return type of a property decorator function must be either 'void' or 'any'. Unable to resolve signature of property decorator when called as an expression. Type 'TypedPropertyDescriptor' is not assignable to type 'void'.
To overcome this issue and successfully implement custom decorators for field validation, I need to find a way to make my decorators capable of calling services. This will allow me to perform more complex validations in the future, such as checking database records for specific data before proceeding.