Skip to content

Instantly share code, notes, and snippets.

@GeekEast
Created November 26, 2020 04:05
Show Gist options
  • Save GeekEast/1f4d9d201349ab799985e6e935a296ec to your computer and use it in GitHub Desktop.
Save GeekEast/1f4d9d201349ab799985e6e935a296ec to your computer and use it in GitHub Desktop.
Learning Note for Nest.js

Read & Learn

Decorators

Decorator Entity
@Request(), @Req() req
@Response(), @Res()* 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]
@Ip() req.ip
@HostParam() req.hosts

Generators

  • controller nest g controller users
  • module nest g module users
  • service nest g service users

Controller

  • deal with incoming request and return response.
  • generator nest g controller users

Module

  • module is the place where you register your controller
  • module is used to organize the codebase.
  • module is always singleton.
  • nest g controller users will automatically register controller in app.module.ts

Providers

  • it can inject dependencies.(DI is a pattern following the Open-closed princile)
  • include services, repositories,factories, helpers and so on.
  • decorators: @Injectable

Services

  • create a service nest g service users

Scope

  • limit lifetime of providers within the application's lifetime
  • for example. scope to a request lifttime.

Middleware

  • called before the route handler
  • the same in express
  • config routes here

Exception

  • nest has built-in gloabl error handler
  • you can throw error with http code
@Get()
async findAll() {
  throw new HttpException({
    status: HttpStatus.FORBIDDEN,
    error: 'This is a custom message',
  }, HttpStatus.FORBIDDEN);
}

Questions

  • What about naming conventions in Nest.js?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment