지난번 개발한 부분까지 Postman을 통하여 테스트해보았어요. 이번에는 backend api 테스트 환경에서 많이 쓰이는 swagger를 통해 테스트를 해보도록 합니다.

먼저, 프로젝트에 swagger 설정하는 것 부터 시작해 보겠습니다.

 

1. swagger 설치

$ npm install --save @nestjs/swagger swagger-ui-express

npm을 이용하여 swagger를 설치 합니다.

 

2. swagger 설정

main.ts에서 SwaggerModule을 이용하여 설정해줍니다.

소스코드는 아래와 같은데, SwaggerConfig를 이용하여 SwaggerModule의 도큐먼트를 생성하고 생성한 도큐먼트를 가지고 SwaggerModule을 설정하는 코드입니다.

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule } from '@nestjs/swagger';
import { SwaggerConfig } from './shared/conf/swagger.config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

  const swaggerUiEndpoint = '/swagger';
  const document = SwaggerModule.createDocument(app, SwaggerConfig);
  SwaggerModule.setup(swaggerUiEndpoint, app, document);

  await app.listen(3000);
}
bootstrap();

swaggerUiEndpoint를 '/swagger'로 하였기에 swagger의 주소는 'http://localhost:3000/swagger/'가 된다.

설정은 너무도 간단하죠? 그럼 SwaggerConfig부분을 살펴보도록 하겠습니다.

Config를 알아야 원하는 설정을 하여 사용할 수 있으니까요!

 

3. swagger  config

'swagger.config.ts'파일을 열어보면 코드가 가시적으로 잘 되어 있는데요. 저는 jwt의 bearer를 사용하기 위해

.addBearerAuth 부분을 수정했습니다.

import { DocumentBuilder } from '@nestjs/swagger';

export const SwaggerConfig = new DocumentBuilder()
  .setTitle('bcheck back auth')
  .setDescription('bcheck backend auth microservice')
  .setVersion('3.0.0')
  // .setHost('localhost:3000')
  //.setBasePath('/')
  // .setSchemes('http')
  .setExternalDoc('For more information', 'http://swagger.io')
  .addTag('Application', 'bcheck-back-auth')
  .addBearerAuth(
    {
      type: 'http',
      scheme: 'bearer',
      name: 'JWT',
      in: 'header',
    },
    'access_token',
  )
  .build();

그리고 swagger에 api들이 보이도록 설정해 보겠습니다.

 

4. api 설정

'app.controller.ts'를 살펴보면 @ApiOperation, @ApiCreatedResponse, @ApiResponse, @ApiBody가 보입니다.

@ApiOperation({
    summary: '사용자 login',
    description: '추후 cognito 연결, usersService에 등록된 사용자 login',
  })
  @ApiCreatedResponse({
    schema: {
      example: {
        access_token:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyRW1haWwiOiJzb3J5NTMzOUBnbWFpbC5jb20iLCJzdWIiOjEsImlhdCI6MTY0NzgyMjQxMCwiZXhwIjoxNjQ3ODIyNDcwfQ.NpWT0a2VxTLPqbl3ZHwqlNYh4Rwwhv0p0WWgUpaY3CE',
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  @ApiBody({ type: UserDto })
  @UseGuards(LocalAuthGuard)
  @Post('/login')
  async login(@Body() user: UserDto) {
    // return req.user;
    return this.authService.login(user);
  }

@ApiOperation : api에 대한 설명

@ApiCreatedResponse : request 성공했을 때 반환될 response

@ApiResponse : request에 대한 repsonse의 직접 설정

@ApiBody : body로 넘겨줄 형태 지정

각각의 설정을 위와 같이 한 경우 아래의 화면처럼 실행됩니다.

 

 

userEmail, password를 입력하여 access_token이 반환되는 /auth/login api에 대한 swagger가 완성되었습니다.

 

5. Try it out

실제로 테스트를 해보겠습니다. 'Try it out'버튼을 클릭하면 'Request body'부분이 확장됩니다.

해당 부분에 body로 넘겨줄 데이터를 json형태로 입력하고 'Execute'하면 아래에 Responses가 보이게 됩니다.

request에 대한 response가 정상적으로 이루어지는 것을 확인할 수 있어요.

앞으로 만들 api에 대해서도 @데코레이터 잘 달아서 swagger로 테스트할 수 있도록 구현해보겠습니다.

728x90
반응형

+ Recent posts