티스토리 뷰

BACKEND

[nestjs] versioning 기능 이용하기

나를찾는아이 2022. 9. 19. 13:36
728x90
반응형

https://docs.nestjs.com/techniques/versioning#versioning

 

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

 

rest api를 설계할때 아래와 같이 버전을 포함하여 url을 설계할수 있습니다

 

POST /v1/users

GET /v1/users

 

이런식으로 말이죠

 

실제로도 많은 API들이 유사한 방식으로 API 버저닝을 하고 있습니다

 

가까운 예로 트위터만 살펴봐도

 

GET /2/tweets/search/recent

 

맨앞에 숫자를 통해 버저닝을 하고 있습니다

 

 

 

nestjs에서는 프레임워크상에서 versioning 기능을 제공하고 있습니다

 

버저닝도 여러가지 형태로 지원을 하고 있습니다

 

URI Versioning

Header Versioning

Media Type Versioning 

 

이중에서 가장 흔히 사용되는 방법이 글 처음에 알려드렸던 uri 에 직접 표기하는 방식입니다

 

 

아래의 코드를 볼까요

 

URI 형태의 버저닝 기능을 활성화하고, 그에 맞는 컨트롤러를 생성했습니다

 

  app.enableVersioning({
    type: VersioningType.URI,
  });

 

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

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

  @Version('1')
  @Get('hello')
  getHello(): string {
    return this.appService.getHello();
  }

  @Version('2')
  @Get('hello')
  getHello1(): string {
    return this.appService.getHello1();
  }
}

 

@Version 어노테이션에 입력한 string이 버전이 됩니다

 

같은 @Get('hello') 경로를 가졌지만 버전이 서로 다릅니다

 

이를 통해 우리는 코드상에서도 이 두개의 함수가 같은 역할을 하는 서로 다른 버전의 함수구나 라는것을 한눈에 알수 있습니다

 

 

nestjs가 실행될때 이렇게 버전이 매핑되어있는것을 확인할수 있습니다

[Nest] 47488  - 2022. 09. 10. 오후 12:29:48     LOG [RouterExplorer] Mapped {/hello, GET} (version: 1) route +0ms
[Nest] 47488  - 2022. 09. 10. 오후 12:29:48     LOG [RouterExplorer] Mapped {/hello, GET} (version: 2) route +1ms

 

그리고 실제로

 

GET /v1/hello
GET /v2/hello

 

이렇게 활용됩니다

 

기본적으로 입력한 버저닝에  "v"가 prefix되어있습니다

 

v가 맘에 들지 않는 경우

 

  app.enableVersioning({
    type: VersioningType.URI,
    prefix: 'api',
  });

 

직접 다른 prefix를 설정할수 있습니다

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함