카테고리 없음

NestJS로 API 만들기

Santino 2023. 2. 13. 01:57

1. @nestjs/cli 설치(터미널)

 - nest js 공식 홈페이지 https://docs.nestjs.com/

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac

docs.nestjs.com

 

$ npm i -g @nestjs/cli
$ nest new project-name

 

* 실행 순서

git remote add
git remote add origin

src에서 app.controller.ts.spec파일 지움
(일단 중요하진 않음 / 나중에 다시 생성 예정)
 
터미널에서
npm run start:dev로 nest js 실행
localhost:3000에서 hello world가 뜲

AppModule에 보면,
@Module({}) 이런식으로 함수를 만들어서 사용
(데코레이터라고 함)

 

 

* 간단한 정보

 

* app.controller.ts에서 바로 @Get()함수를 실행이 가능한데,
  왜 app.service.ts가 필요할까?
 : nestjs는 컨트롤러와 비지니스로직이랑 구분하고 싶어함
   컨트롤러는 그냥 url를 가져오는 역할 + function을 실행하는 정도까지만.
    
  비지니스로직은 서비스로 감

 

 

* 앱 실행 원리(동작 순서)

 

1) main.ts에서 
   # 1에 위치한 Appmodule의 위치를 찾으려면

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


2) app.module.ts에 가서 확인 가능
   controllers와 providers 2가지의 활용 순서는..(아래 3번에 이어서)

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

3) app.controller.ts에서 
   #2번은 기본 실행값이고
   #3번은 getHello()를 호출 하는 것
   #4번은 getHello()를 호출 후 return되는 값
   근데 return값이 appService의 getHello()라고 되어있어서, 
   appService로 가보면..(아래 4번에 이어서)

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

  @Get()                                                    <<< # 2
  getHello(): string {                                      <<< # 3
    return this.appService.getHello();                      <<< # 4
  }
}


4) Injectable(주입 가능한)
   여기서 getHello()를 호출하면,
   return 값으로 Hello World가 출력이 되고,
   이 값이 localhost:3000에서 출력되어 나옴

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

 

* app.controller에서 함수 실행값 이름과 return에서의 호출 이름이 같진 않아도 됨

app.controller.ts
#1에 있는 sayHello()라는 이름과,
#2에 있는 getHi()의 이름이 같진 않아도 됨
(그래도 무조건 getHi()는 app.service.ts에 있어야함 


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

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
  @Get('/hello')
  sayHello(): string {                                       <<< # 1
    return this.appService.getHi();                          <<< # 2
  }
}

app.service.ts
#3에서의 getHi()함수가 실행이 됨 

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
  getHi(): string {                                                     <<< # 3
    return 'Hi Nest';
  }
}

 

** app.controller랑 app.service지우고 다시 생성해보기
 

터미널에서 nest -h 입력하면 사용가능한 도구들이 나옴
  1) nest g co (nest generate contoller의 줄임말)

** 근데 nest g co해서 파일이름을 movies로 했는데,
   폴더랑 파일에 -movies라고 나오는 이유는 뭐지?
   
   ------------------------------------------------------
   
* insomnia에서 http://localhost:3000/movies/1
  GET으로 보내면 결과값 도출 가능
** Nest js에서는 무언가 필요하면 직접 요청해야함
   예_ id값을 알고 싶으면, parameter로 전달 해줘야 함
   = @Get('/:id')                                              <<< #1
     getOne(@Param('id') MovieId: string) {                    <<< 'id'이름은 #1과 같아야함
                                                               <<< MovieId이름은 #2와 같아야함
     return `This will return one movie with the id: ${MovieId}`; <<< #2
     }

***여기서 id = id, movieId = movieId 같아야 함 무조건

 

*  Post로 JSON형식의 { } Body를 보내려면,

#1의 위치에 @Body()를 작성해줘야 함
그리고 insomnia에서 POST파일 안에서 { } JSON형식으로 body값을 입력해주면 됨.

@Post()
  create(@Body() movieData) {           <<< # 1
  return 'This will create a movie';
}