View

TIL | NestJS_REST_API_Settings

Melody:) 2021. 10. 11. 11:32

NestJS란?

  • 효율적이고 확장 가능한 Node.js 서버 측 애플리케이션을 구축하기위한 프레임 워크. 즉, Node.js 위에서 움직이는 프레임워크
  • 다른 node.js프레임워크에 없는 것을 가지고 있다.
  • node.js에서는 url, controller, templete, middle ware 등을 어느 위치에 두든 상관 없이 돌아가게 할 수 있으나,
  • Nest.js에서는 구조와 규칙이 정해져 있다.
  • 객체지향 프로그래밍과 함수형 프로그래밍, 심지어는 함수 반응형 프로그래밍의 요소도 일부분 사용하는 것을 알 수 있다.

** NestJS 공식 홈페이지 : 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](https://docs.nestjs.com/)


NestJS는 Express위에서 돌아가는 프레임워크이다.

하지만 추가로 fasify라는 라이브러리도 사용 하고 있는데,

플랫폼이나 어플리케이션에 Req, Res 같은 데코레이터를 이용해 

Express에 접근 할 수있으나, 이를 지양하는게 좋다.

그 이유는 성능향상을 위해 Express와는 다른 방법을 지원하는 Fasify를 사용할 수 도 있기 때문이다.


getAll(@Req() req, @Res() res): Move[] {

  res.json()
}

 

 


 

NestJS 설치

$ npm i -g @nestjs/cli


새 프로젝트 시작

$ nest new project-name

 


insomnia 설치 : https://insomnia.rest/download


새 프로젝트 생성 후 서버 run

  1. pakage.json의 script를 살펴보자. 우리는 실행시 아래 명령문으로 실행 할 예정이다.

npm run start:dev

 

  1. localhost:3000에 접속해보자!

 

생성된 파일

1. main.ts

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


// 1. main.ts의 이름은 고정이다.
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();
  • NestJS가 시작하는 곳
  • 1개의 어플리케이션(user, products, 등등..)은 1개의 모듈을 갖는다.

2. app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
// 2. 데코레이터 : 클래스에 함수기능을 추가할 수 있음. 간단히 말해 클래스 위의 함수이며, 클래스를 위해 움직임.
@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
  • 어플리케이션의 root 라고 보면됨.
  • controllers : url을 가져오고 함수를 실행시킴.(express의 라우터와 같은 존재)

3. 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() : express의 get 라우터와 같은 존재
    @Get('/hello')
    sayHello(): string {
      return 'Hello everyone';
    }
    => local:3000/hello로 실행시켰을 경우 'Hello everyone'이 호출된다.

  • post를 쓰다면?
  @Post('/hello')
  sayHello(): string {
    return 'Hello everyone';
  }

웹페이지에 아래와 같은 에러가 발생한다.


service

그렇다면, controller안에서도 충분해 값을 리턴시켜, 화면에 나타낼 수 있는데,
왜 service가 필요할까??
이를 이해하기 위해서는 NestJS의 구조와 아키텍처를 알 필요가 있다.
NestJS는 컨트롤러를 비지니스 로직과 구분짓고 싶어하는데,

import { Controller, Get, Post } 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')
  getHi(): string {
    return this.appService.getHi();
  }
}

컨트롤러는 단순히 url을 가져와서 function을 실행시키는 정도이나,
나머지 비트지스 로직은 service로 간다.
service는 일반적으로 실제로 function을 가지는 부분이며, 만약 아래의 정의된 AppService로 들아가면,

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

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

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

getHello()이라는 간단한 function이 들어있는 것을 볼 수 있다.
이것이 바로 NestJS의 컨벤션이다.


4. app.service.ts

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

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

app.service의 값을 수정해보자.

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

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

 

'NestJS' 카테고리의 다른 글

TIL | NestJS_REST_API_Service  (0) 2021.10.11
TIL | NestJS_REST_API_Controller  (0) 2021.10.11
TIL | TypeScript_기본문법2  (0) 2021.10.10
TIL | TypeScript_기본 문법1  (0) 2021.10.10
TIL | Typescript_Setting_초기개발환경세팅  (0) 2021.10.07
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31