W14D2 Using Nest.js

Jin Bae·2023년 2월 15일
0

스파르타코딩클럽

목록 보기
32/35

Installing Nest.js and creating a new project

Nest.js required Node.js and it only uses NPM (NOT yarn or any other package managers).

To install Nest.js as a global command:

npm i -g @nestjs/cli

Use the nest command to see all the available options.

To create a new project:

nest new sparta-nest

새 프로젝트가 생성이 안 될 때 참고: https://velog.io/@librarian/ts-jest-%EC%84%A4%EC%B9%98-%EC%95%88%EB%90%98%EB%8A%94-%ED%98%84%EC%83%81

❗❗ Always select the NPM package manager as it is most compatible with Nest.js.

main.ts

❗❗ Never change the name of src/main.ts as it is a file referenced by Nest.js

main.ts is composed of the following code.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Here, const app = await NestFactory.create(AppModule); is a command that creates an instance of the Nest.js application using the AppModule root module.

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

@ is a keyword called decorator. The decorator tells Nest.js what role a certain class or function performs. Here, it delcares to Nest.js that the AppModule class will act as a module in the app.

The exports property can also be added to the decorator.

Properties of @Module:

  • imports
    - An array of necessary modules for the current module
    • The modules here export the provider (service) (?)
    • One of the most commonly imported module is the HttpModule (module that calls API)
    • The TypeOrmModule can also be imported
  • controllers
    - Declares the controller used in the module
  • providers
    - Declares the service used in the module
  • exports
    - The modules declared here export the selected service
    • To use this service in another module, it must be declared in exports

app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

AppController acts as the controller of the AppModule.

The following code is the dependency injection (DI) of AppService to AppController. The IoC container of Nest.js tracks the class with the decorator @Injectable or @InjectRepository (in app.service.ts) and injects dependency synchronously when the web application runs.

constructor(private readonly appService: AppService) {}

The @Get decorator declares to run this function when a HTTP GET request is received. There are also @Post, @Put, and @Delete.

@Get()
  getHello(): string {
    return this.appService.getHello();
  }

Inversion of Control (IoC, 제어 역전)

https://docs.nestjs.com/fundamentals/custom-providers
https://teamsparta.notion.site/Nest-js-10-IoC-DI-30d3cd76174440d7b29308513c2cf3a1
IoC means Inversion of Control (제어 역전), where the control flow of the program is inverted. Simply put, you delegate control to the framework.

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

In this code:

export class AppController {
  constructor(private readonly appService: AppService) {}
  • AppController is dependent on AppService.
  • However, it does not interfere with the AppService life cycle.
  • The controller only uses the object provided.
    This role is called IoC and with its help, we do not need to be concerned about the object's life cycle.

Dependency Injection (DI, 의존성 주입)

DI is only of the most basic IoC technique.
As opposed to IoC where the framework controls, DI is where the developer will manage the classes the framework needs.

app.controller.spec.ts

Code that tests the app.controller.ts.

The script to run the test code is already declared in package.json.

0개의 댓글