Due to the lack of support for decorators on local variables in ECMAScript2016/Typescript, it is not possible to use decorators in the service as described in the question.
However, class-validator offers a non-decorator implementation for its validation functions.
The class-validator Github page states: https://github.com/typestack/class-validator#manual-validation
The Validator has various methods that allow non-decorator based validation:
import { isEmpty, isBoolean } from 'class-validator';
isEmpty(value); isBoolean(value);
Therefore, the same goal can be achieved with code similar to this:
import { Injectable } from "@nestjs/common";
import { CreateDto } from "./dto/create.dto";
import { isEmpty, isInt } from "class-validator";
@Injectable()
export class TestValidationService {
test(createDto: CreateDto) {
const {name, age} = createDto;
if (isEmpty(name)) {
throw "There is no name.";
}
if (!isInt(age)) {
throw "Age is not int."
}
return createDto;
}
}
If you prefer not to use individual methods within the service, you can still decorate your DTO and use the validate method from class-validator.
For example:
import { IsInt, IsNotEmpty } from "class-validator";
export class CreateDto {
@IsNotEmpty()
name: string;
@IsInt()
age: number
}
And in your service:
async testWithValidate(createDto: CreateDto) {
const validationResult = await validate(createDto);
}