NestJS로 API 만들기

https://nomadcoders.co/nestjs-fundamentals


노마드코더 강의를 참고하고 있습니다.

 


결과 화면

 


Nest.js 설치하기

NestJs 설치에 대한 설명은 아래 링크를 참고한다.

https://jae-study.tistory.com/78

 

[Nest] #1 NestJs 설치하기

NestJS(Nest)란? https://docs.nestjs.com/ NestJs는 효율적이고, 확장 가능한 Node.js 서버 애플리케이션을 구축하기 위한 프레임워크이다. 프로그레시브 Javascript를 사용하고, Typescript로 구축되어 Typescript를

jae-study.tistory.com

 


Nest.js

네스트(Nest.js)는 Node.js를 위한 서버 사이드 애플리케이션을 개발하기 위한 프레임워크이다.

애플리케이션을 구성하는데 모듈, 컨트롤러, 서비스의 개념을 사용한다.

 

모듈 (Module)

@Module 데코레이터를 사용해 모듈을 정의하고, 해당 모듈은 컨트롤러, 서비스, 미들웨어 및 다른 컴포넌트들을 그룹화하는 방법을 제공한다.

Nest.js 애플리케이션을 여러 모듈로 구성되며, 의존성 주입을 통해 모듈 간에 서비스 및 기능을 공유하고, 코드의 재사용성을 높인다.

 

  • src/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 {}

 

컨트롤러 (Controller)

@Controller 테코레이터를 사용해 컨트롤러를 정의하고, 해당 컨트롤러에는 특정 엔드포인트(경로)에 대한 라우팅 정보가 포함된다.

또한 각 컨트롤러는 HTTP 메서드(GET, POST 등)에 메핑 되며, HTTP 요청을 처리하고 응답하는 역할을 수행한다.

 

  • src/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();
  }

  @Get('/hi')
  sayHello(): string {
    return this.appService.getHi();
  }
}

 

서비스 (Service)

@Injectable() 데코레이션을 사용해 서비스를 정의하고, 해당 서비스에는 필요한 비즈니스 로직이나 데이터를 구현한다.

컨트롤러에서 호출되어 컨트롤러에게 데이터가 기능을 제공하는 역할을 한다.

 

  • src/app.service.ts
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello Nest!';
  }

  getHi(): string {
    return 'Hi Nest!';
  }
}

 

주의

데코레이터는 함수나 클래스랑 붙어있어야 한다. (스페이지 또는 엔터를 사용하면 안 된다.)

+ Recent posts