I'm validating my DTOs with the class-validator package. I enabled the transformation via
app.useGlobalPipes(
new ValidationPipe({
transform: true,
}),
);
in my main.ts file as described in the docs
https://docs.nestjs.com/techniques/validation#transform-payload-objects
I have a optional configuration field in my DTO. This field should be transformed to an empty object if it doesn't exist. The transformation decorator is described here
https://docs.nestjs.com/techniques/serialization#transform
I was hoping to come up with this solution:
export class MyDTO {
#IsObject()
#IsOptional()
#Transform(configuration => configuration || {})
public configuration: object;
}
When I call my API route
#Post()
public create(#Body() myDTO: MyDTO): void {
console.log(myDTO);
}
with an empty body, so without the field configuration my MyDTO instance is
{}
although I would expect it to be
{
configuration: {}
}
What is wrong or what am I missing? I tried to debug the code and it never hits the transformation function. So the #Transform doesn't trigger.
Update
It seems I have to do this
#IsObject()
#IsOptional()
#Transform(configuration => configuration || {}) // will be used if the field exists
public configuration: object = {}; // will be used if the field doesn't exist
The initial value will be used if you pass in an empty body. The transformation only runs if you pass in the field but assign a value like null to it.
Gonna go ahead n put this here too: why not just let typescript manage the default value with setting the value like
export class MyDTO {
#IsObject()
#IsOptional()
public configuration: object = {};
}
That way, if you get a value, great, and if it isn't there, class-transform will put the correct value there.
Looks like there is more discussion about solutions here.
Related
There's a method that accepts an intersection of a few DTOs:
export type RegisterUserDto = RegisterCommonUserDto
& RegisterLocationProviderDto
& RegisterFighterDto;
The method looks like that:
#Post('register')
public async registerUser(#Body() registerUserDto: RegisterUserDto): Promise<any> {
// method code
}
The controller itself is decorated with #UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
So when a DTO is a class the validation works, but now it's a type and the class-validator just fails to react to incorrect data, I mean all its decorators like #IsEmail(), #IsPhoneNumber() etc just don't work.
What should I do to make it work?
I've managed to solve this issue with the help of this library https://www.npmjs.com/package/ts-mixer implementing multiple inheritance. So now my RegisterUserDto looks like this.
export class RegisterUserDto extends Mixin(RegisterCommonUserDto, RegisterLocationProviderDto, RegisterFighterDto) {}
However I would appreciate other solutions.
I have NestJS API, which has a PATCH endpoint for modifying a resource. I use the class-validator library for validating the payload. In the DTO, all fields are set to optional with the #IsOptional()decorator. Because of that, if I send an empty payload, the validation goes through and then the update operation errors.
I am wondering if there is a simple way to have all fields set to optional as I do and at the same time make sure that at least one of them is not empty, so the object is not empty.
Thanks!
I don't know if it is possible using DTO.
For that purpose I use Pipes. Like this:
Injectable()
export class ValidatePayloadExistsPipe implements PipeTransform {
transform(payload: any): any {
if (!Object.keys(payload).length) {
throw new BadRequestException('Payload should not be empty');
}
return payload;
}
}
Whilst studying NestJS I encountered an issue, I have the following DTO:
export default class SearchNotesDto {
query: string;
createdAfter: Date;
createdBefore: Date;
}
Which I wish to get when a GET request is made to an endpoint, which is handled by the following function in my controller:
#Get()
getNotes(#Query() searchNotesDto: SearchNotesDto): Note[] {
if (Object.keys(searchNotesDto).length) {
return this.notesService.searchNotes(searchNotesDto);
}
return this.notesService.getAllNotes();
}
My problem is that createdAfter and createdBefore are strings in searchNotesDto, and I wish to work with the Date object, is there a way to implicitly convert those fields to a Date?
#Query will serialize all properties to type string because that's how query string works in terms of HTTP Request. You will need to utilize a Pipe to transform your query to the right shape of data.
https://docs.nestjs.com/pipes
export class SearchNotePipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
// value will be your `searchNotesDto`
const notesDto = new SearchNotesDto();
// do your transformation here
return notesDto;
}
}
I have a class CreateFolderDto with two readonly fields:
export class CreateFolderDto {
public readonly name: string
public readonly user_id: number
}
I have a controller which is:
#UseGuards(AuthGuard('jwt'))
#Post()
public create(#Request() req, #Body() createFolderDto: CreateFolderDto) {
return this.folderService.create(createFolderDto)
}
The request send to my controller is a good one, I only send the name in json format with an accessToken in the header. The accessToken permit me to get my user_id from the request with req.user.id.
The DTO field user_id is not automatically filled. I would like to fill it automatically.
Is it a way to auto-fill my createFolderDto.user_id variable ?
#Body only wraps actual request body into instance of the CreateFolderDto class. As the body which comes to your endpoint has no such a field, you need to add it manually.
Normally, aggregated fields could be added with custom constructor of your DTO:
export class CreateFolderDto {
public readonly name: string
public readonly session_uuid: string
constructor(bodyValue: any = {}) {
this.name = bodyValue.name
this.session_uuid = generateUuid()
}
}
But in your case, user is attached to request itself, so I believe you have the following options:
Check out your code which attaches the user to request itself. If you are using JWT Auth described in NestJS docs, you cannot do this that way.
You can write custom Interceptor:
Injectable()
export class ExtendBodyWithUserId implements NestInterceptor {
async intercept(context: ExecutionContext, next: CallHandler) {
const request = context.switchToHttp().getRequest()
request.body.user_id = request.user
return next.handle()
}
}
// usage
#UseGuards(AuthGuard('jwt'))
#UseInterceptors(ExtendBodyWithUserId)
#Post()
public create(#Request() req, #Body() createFolderDto: CreateFolderDto) {
return this.folderService.create(createFolderDto)
}
Last but not least, some personal recommendation. Consider how much you will use this interceptor as an extension, as too many of 'extras' like this bloat the codebase.
I would recommend to change the folderService signature to:
create(createFolderDto: CreateFolderDto, user: User), where folder dto has only the name, without user-related entry. You keep the consistency, separation and clear intentions. In the implementation of create you can just pass user.id further.
And going this way, you don't have to write custom interceptors.
Pick your way and may the consistency in your codebase be with you!
I am writing a NestJS application. Some of the endpoints support sorting e.g. http://127.0.0.1:3000/api/v1/members?sort=-id&take=100 Which means sort by id descending.
This parameter arrives as a #Query parameter and is passed to my service. This service transforms it into an object which is used by TypeORM:
{
id: 'DESC'
}
I don't want to call this conversion method manually every time I need sorting.
I've tried an intercepter but this one could not easily change the request parameters into the desired object.
A pipe worked but then I still need to add #Query(new SortPipe()) for every endpoint definition.
Another option is in the repository itself. The NestJS documentation is very well written, but misses guidance in where to put what.
Is there someone who had a similar issue with converting Query parameters before they are used in NestJS, and can explain what approach is the best within NestJS?
This question might look like an opinion based question, however I am looking for the way it is supposed to be done with the NestJS philosophy in mind.
Pipes are probably the easiest way to accomplish this. Instead of adding your pipe for every endpoint definition you can add a global pipe that will be called on every endpoint. In your main.ts:
async function bootstrap() {
...
app.useGlobalPipes(new SortPipe());
...
}
You can then create a pipe like this:
import { PipeTransform, Injectable, ArgumentMetadata } from '#nestjs/common';
#Injectable()
export class SortPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
const { type } = metadata;
// Make sure to only run your logic on queries
if (type === 'query') return this.transformQuery(value);
return value;
}
transformQuery(query: any) {
if (typeof query !== 'object' || !value) return query;
const { sort } = query;
if (sort) query.sort = convertForTypeOrm(sort);
return query;
}
}
If you do not want sort value on ALL endpoints to be automatically converted, you can pass custom parameter to #Query(), for example #Query('sort'). And then:
transform(value: any, metadata: ArgumentMetadata) {
const { type, data } = metadata;
// Make sure to only run your logic on queries when 'sort' is supplied
if (type === 'query' && data === 'sort') return this.transformQuery(value);
return value;
}