TIL(swagger사용하기)
2024. 7. 25. 22:21ㆍTIL
💡NestJS에서 swagger사용하기
의의
swagger란 apI를 문서화하고, 테스트할 수 있는 인터페이스를 제공하는 도구로 API 문서를 따로 작성할 필요없이 코드를 수정하면서 API 문서를 같이 수정할 수 있는 장점을 가지고 있다.
사용방법
1. swagger 라이브러리 설치
npm install --save @nestjs/swagger swagger-ui-express
2. main.ts에 적용하기
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; <<== swagger import 해오기
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const port = configService.get<number>('SERVER_PORT');
//swagger 설정
const config = new DocumentBuilder()
.setTitle('GuBu Service')
.setDescription('내 구독을 부탁해~')
.setVersion('1.0')
.addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }) // JWT 사용을 위한 설정
.build();
app.useGlobalPipes(
new ValidationPipe({
transform: true,
}),
);
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document, { // '/api' 경로에서 Swagger UI 제공
swaggerOptions: {
persistAuthorization: true, // 새로고침 시에도 JWT 유지하기
tagsSorter: 'alpha', // API 그룹 정렬을 알파벳 순으로.
operationsSorter: 'alpha', // API 그룹 내 정렬을 알파벳 순으로
},
});
await app.listen(port);
}
bootstrap();
3. localhost:3000/api 접속시 화면
'TIL' 카테고리의 다른 글
TIL ( 해시테이블과 이진검색트리 ) (0) | 2024.07.29 |
---|---|
TIL ( 깊은 복사와 얕은 복사 & jwt ) (0) | 2024.07.26 |
TIL(Proxy) (2) | 2024.07.24 |
TIL ( crypto-js 란) (0) | 2024.07.23 |
TIL ( 팀프로젝트-초기설계 ) (0) | 2024.07.22 |