[Nest.js] 공부하기 - Fundamentals

Junsoo Choi·2021년 7월 8일
0

Fundamentals

DI fundamentals

Dependency injection is an inversion of control(IoC) technique wherein you delegate instantiation of dependencies to the IoC container, instead of doing it in your own code imperatively.

// cats.service.ts
@Injectable()
export class CatsService {
  // ...
}

@Injectable() declares CatsService class as a class that can be merged by the Nest IoC container.

// cats.controller.ts
@Controller('cats')
export class CatsController {
  constructor(private catsService: CatsService) {}
  // ....
}

CatsController declares a dependency on the CatsService token with constructor injection.

// app.module.ts
@Module({
  controllers: [CatsController],
  providers: [CatsService],
})

Associate token CatsService with the class CatsService from the cats.service.ts file.

여기서의 token은 cats.controller.ts의 constructor에서 선언한 것을 뜻하는 것 같다.

Injection scopes

By default, in Nest, almost everything is shared across incoming requests. However, there are edge-cases where request-based lifetime may be desired behavior.

A provider can have any of the following scopes:

  • DEFAULT: singleton으로 entire app이 share
  • REQUEST: 매 incoming request마다 new instantiation
  • TRANSIENT: injection하는 consumer마다 새로운 dedicated instance

Execution context

Nest provides several utility classes that help make it easy to write apps that function across multiple application contexts. These utilities provide information about the current execution context which can be used to generate guards, filters, and intercepters that can work across a broad set of controllers, methods, and execution contexts.

(위에서 언급한 utility class들)

ArgumentsHost class

ArgumentsHost class provides methods for retrieving the arugments being passed to a handler. It allows choosing the appropriate context(e.g., HTTP, RPC, WebSockets) to retrieve args from.

The framework provides an instance of ArgumentsHost typically referenced as a host parameter.

const [req, res, next] = host.getArgs();

// type을 지정하여 더 robust하게
const ctx = host.switchToHttp();
const request = ctx.getRequest<Request>();
const response = ctx.getResponse<Response>();

Lifecycle Events

A Nest application, as well as every applciation element, has a lifecycle managed by Nest. Nest provides lifecycle hooks that give visibility into key lifecycle events, and the ability to act when they occur.

profile
Youtube: 개발자준

0개의 댓글

관련 채용 정보