I want to access the res
object to send httpOnly
cookies and need to validate body with DTO.
but every time i try to do it something go wrong what is the right order for these params?
There is no strict order that needs to be followed. Each controller method may use decorators for retrieving different things (see controller docs: https://docs.nestjs.com/controllers)
Let's imagine you are building an endpoint for handling some kind of search using a POST request and a payload. Nest returns some results and sets cookies with the latest performed search timestamp.
That sounds like your requirements, right?
Make sure you followed cookies documentation and installed all dependencies together and configured cookie parser middleware: https://docs.nestjs.com/techniques/cookies
import { IsInt, IsNotEmpty } from 'class-validator';
export class SearchBodyDto {
@IsNotEmpty()
searchPhrase: string;
@IsInt()
page = 1;
}
import { Request, Response } from 'express';
import { Body, Controller, Post, Req, Res } from '@nestjs/common';
@Controller()
export class AppController {
@Post('/search')
async search(
@Body() body: SearchBodyDto,
@Req() req: Request,
// passthrough:true here leaves response handling to framework.
// Otherwise you would need to send response manually, like: `res.json({data})`
@Res({ passthrough: true }) res: Response,
) {
const currentTimestamp = new Date().toISOString();
// Save to cookies current timestamp of search.
res.cookie('lastSearch', currentTimestamp, { httpOnly: true });
return {
// Return last search timestamp and fallback to current timestamp.
lastSearch: req.cookies.lastSearch ?? currentTimestamp,
// Validated search phrase from DTO.
searchPhrase: body.searchPhrase,
// Page by default 1.
page: body.page,
// Some example search results.
searchResults: ['water', 'wind', 'earth'],
};
}
}
Now when you do a request to the endpoint, you will see the latest search time in a response: postman example, and also that value will be set to 'lastSearch' cookie.
The payload still will be validated using decorators on DTO.
There are no order.
Also, they are parameter decorator factories, not parameters.