1- import { Controller , Get , Post , Body } from '@nestjs/common' ;
1+ import { Controller , Get , Post , Body , Res } from '@nestjs/common' ;
22import { ApiTags } from '@nestjs/swagger' ;
33import { ZodResponse } from 'nestjs-zod' ;
44import { CreateStarshipFormDto , StarshipDto , StarshipListDto , Starship } from './starships.dto' ;
5+ import { Response } from 'express' ;
56
67@ApiTags ( 'Starships' )
78@Controller ( 'api/starships' )
@@ -83,4 +84,31 @@ export class StarshipsController {
8384
8485 return newStarship ;
8586 }
87+
88+ /**
89+ * This example shows how to use the @Res decorator to set headers on the
90+ * response. Note that in order for `@ZodResponse` to work, we need to return
91+ * the data from the function and use `passthrough: true`. We can't use
92+ * `res.send()`! `res.send()` bypasses the zod nestjs interceptor
93+ *
94+ * For more information, search `passthrough` in the zod documentation page
95+ * for controllers here: https://docs.nestjs.com/controllers
96+ *
97+ * > Nest detects when the handler is using either @Res() or @Next(), indicating
98+ * > you have chosen the library-specific option. If both approaches are used at
99+ * > the same time, the Standard approach is automatically disabled for this
100+ * > single route and will no longer work as expected. To use both approaches at
101+ * > the same time (for example, by injecting the response object to only set
102+ * > cookies/headers but still leave the rest to the framework), you must set
103+ * > the passthrough option to true in the @Res({ passthrough: true })
104+ * > decorator.
105+ */
106+ @Get ( 'headers-example' )
107+ @ZodResponse ( { type : StarshipListDto , description : 'List of all starships' } )
108+ getStarships2 ( @Res ( { passthrough : true } ) res : Response ) {
109+ res . header ( 'X-Example' , 'example' ) ;
110+ return {
111+ data : this . mockStarships ,
112+ } ;
113+ }
86114}
0 commit comments