Nest js Tutorial Series — Part 2: Controllers
The concept of a controller is nothing new, you might have used in MVC (Model view controller) based frameworks. For the most part, controllers are responsible for handling incoming requests and returning responses to the client-side of the application. The routing mechanism ensures which controller should receive which request. A single controller can have more than one route, and different routes can perform different actions.
Before creating a controller you must know what is a typescript decorator and how decorator works. Decorators associate classes with required metadata. You just create a typescript class and annotate with a @controller decorator. Then nest creates a routing map which links requests to the corresponding controllers.
Now If you followed my last part, then there is already a project built by nest-cli and if you go to src folder you will see app.controller.ts
After a controller is created, it needs to be added to the module so that Nest.js can easily recognize it. If you go to src/app.module.ts you will see controller is added to the root ApplicationModule.
Request Object
The request object contains all the HTTP request properties like query string, parameters, HTTP headers, and body (read more here). We can get the values of these properties by built-in decorators such as @Body, @Request() and @Response(), etc.
Below is the list of header decorators with corresponding express mappings.
@Request() -> req
@Response() -> res
@Next() -> next
@Session() -> req.session
@Param(key?: string) -> req.params
/req.params[key]
@Body(key?: string) -> req.body
/req.body[key]
@Query(key?: string) -> req.query
/req.query[key]
@Headers(name?: string) -> req.headers
/req.headers[name]
Resources
Basically, every API endpoint is a resource. Nest provides standard HTTP request endpoint decorators —
@Put()
,@Delete()
,@Patch()
,@Options()
,@Head()
, and@All()
. Each represents its respective HTTP request method.
Status code
Status code by default is 200 for all requests except POST which is 201. We can easily customize by adding @HttpCode(204) decorator.
Response Headers
You can easily customize the header by adding @Header(‘Cache-Control’, ‘none’) or call res.header() as in express.
That’s it, folks.
If you enjoyed this tutorial, please click the 👏 button and share to help others find it! Feel free to leave a comment below.
Next Part → Providers, Services & Dependency Injection