728x90
서버가 버전업 되었을 때 이전 버전의 서버와 통신하던 프론트를 위해 버전을 나눠놓는 것.
- URI Versioning: URI에 버전이 전달된다. /v1/movie
- Header Versioning: Header에 버전이 전달된다. version: 1
- Media Type Versioning: Header의 Accept 키에 버전이 전달된다. Accept: application/json;v=2
- URI Versioning
- 글로벌 적용
// main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('v1');
await app.listen(3000);
}
bootstrap();
prefix를 설정하면 모든 api 앞에 해당 값을 넣어줘야함
ex) localhost:300/auth/login => localhost:300/v1/auth/login
하지만 너무 글로벌 하기 때문에
// main.ts
app.enableVersioning({
type: VersioningType.URI,
defaultVersion: '1',
});
로 변경하고,
// app.module.ts
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(BearerTokenMiddleware)
.exclude(
{
path: 'auth/login',
method: RequestMethod.POST,
version: '1',
},
{ path: 'auth/register', method: RequestMethod.POST, version: '1' },
)
.forRoutes('*');
}
}
미들웨어에 적용할 수 있음.
여러개 하고 싶다면 version을 리스트로 넣으면 됨.
defaultVersion: ['1', '2'],
{ path: 'auth/register', method: RequestMethod.POST, version: ['1'. '2'] },
- 컨트롤러에 적용
// main.ts
app.enableVersioning({
type: VersioningType.URI,
});
// movie.controller.ts
@Controller({
path: 'movie',
version: '2',
})
export class MovieController {
constructor(private readonly movieService: MovieService) {}
}
이것도 역시 여러개 쓰고 싶으면 version 리스트로 넣어주면 됨.
- Method에 적용
@Get()
@Version('5')
getMoives(
@Query() dto: GetMoviesDto, //
@UserId() userId?: number,
) {
return this.movieService.findAll(dto, userId);
}
- Header Versioning
// main.ts
app.enableVersioning({
type: VersioningType.HEADER,
header: 'version',
});
version 대신 다른거 넣어도 됨. 단지 front에서 해당 값으로 요청해야됨.
- Media Type Versioning
// main.ts
app.enableVersioning({
type: VersioningType.MEDIA_TYPE,
key: 'v=',
});
- 기본값 처리
// movie.controller.ts
@Controller({
path: 'movie',
version: VERSION_NEUTRAL,
})
export class MovieController {
constructor(private readonly movieService: MovieService) {}
}
어느 버전으로 요청 들어와도 다 들어와짐.
// movie.module.ts
providers: [
MovieService_V1,
MovieService
],
대신 버전요청이 필요한 Controller의 경우 해당 Module의 providers에서 앞 순서로 등록해줘야함.
728x90
'코딩 > Nest.js' 카테고리의 다른 글
Testing - 개념과 초기 세팅 (3) | 2024.11.03 |
---|---|
Swagger 2 (0) | 2024.10.27 |
Logging (2) | 2024.10.26 |
Task Scheduling (1) | 2024.10.26 |
Caching (2) | 2024.10.25 |