controller와 비즈니스 로직의 구분을 위해 Service 계층이 존재한다.

controller : 요청된 url을 받아와서 함수를 실행

service : 비즈니스 로직 실행. 실제 로직이 있는 function을 가짐.

//app.service.ts

import { Injectable } from '@nestjs/common';

// 데코레이터
// 클래스 AppService 안에 getHello() 라는 함수가 있음.
// getHello() : string 'Hello World!' 리턴 => localhost:3000을 실행했을 때 화면에 표시된 것.
@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}

지금 AppService라는 클래스에는 getHello()라는 함수만 존재한다.

여기에 함수를 추가하고, 추가한 함수를 controller에서 사용하는 예시를 살펴보자.

  1. AppService 클래스에 getHi() 라는 함수 추가

    // app.service.ts
    import { Injectable } from '@nestjs/common';
    
    @Injectable() // 데코레이터
    export class AppService {
      getHello(): string {
        return 'Hello World!';
      }
    	// AppService 클래스에 getHi() 라는 함수 추가
      getHi(): string { 
        return 'Hi Nest';
      }
    }
    
  2. Controller 에서 AppService의 getHi() 함수 사용하기

    // 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('/hello')
      sayHello(): string {
        return this.appService.getHi();
      }
    }
    

    데코레이터 @Get(’/hello’) 추가.

    이 데코레이터는 ‘/hello’ url로 get 요청이 들어오면, sayHello() 라는 함수를 실행한다.

    sayHello() 함수는 AppService의 getHi() 함수를 호출한다.

    결과적으로 AppService 클래스에 새로 생성한 getHi()라는 함수가 실행된다.