Skip to content

Swagger

Lee Dogyeong edited this page Dec 6, 2020 · 1 revision

배경

개발이 바빠서 api 문서 작성을 소홀히 하게 되었고, 이제 다른 api의 정보를 보려면 코드를 보면서 확인해야 하는 상황이 되었다.

이런 문제 때문에 api 문서를 더 편하게 작성할 수 있도록 Swagger를 사용해 보기로 했다.


설정

주석으로 api문서를 작성하면 Swagger가 파싱해서 보여주는 방식인 것 같다.

필요한 패키지 설치

npm i swagger-ui-express swagger-jsdoc

환경설정

// config/swagger.js
const swaggerDefinition = {
  info: {
    title: 'TOTP App', 
    version: '1.0.0',
    description: 'TOTP App API',
  },
  host: 'https://dadaikseon.com',
  basePath: '/api', 
  servers: ['http://localhost:3000'],
};
// app.js
const swaggerUi = require('swagger-ui-express');
const swaggerJSDoc = require('swagger-jsdoc');
const swaggerDefinition = require('@config/swagger');

const swaggerOptions = {
  swaggerDefinition,
  apis: ['./routes/**/*.js'],
};
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerJSDoc(swaggerOptions)));

이렇게 설정하면 routes 폴더 내에 있는 모든 js파일에서 주석을 파싱하는 것 같고,
localhost:3000/api-docs 로 접속하면 Swagger가 만든 api 문서를 볼 수 있다.


API 문서 작성

jsdoc 방식의 주석으로 작성하며 yaml 포맷으로 작성한다.

/**
 * @swagger
 * /auth/dup-id:
 *  post:
 *    tags:
 *    - auth
 *    description: 아이디 중복 체크를 한 후 결과를 반환한다
 *    consumes:
 *    - "application/json"
 *    produces:
 *    - "application/json"
 *    parameters:
 *    - name: id
 *      in: body
 *      description: 중복체크할 아이디
 *      type: string
 *      required: true
 *    responses:
 *      200:
 *        description: 중복체크 결과
 *        schema:
 *          type: object
 *          properties:
 *            result:
 *              type: boolean
 *      401:
 *        description: csrf에러
 *      500:
 *        description: 기타 오류
 */
router.post('/dup-id', authController.dupId);

작성하면 주석이 굉장히 길어진다. 스키마를 미리 정의해놓을 수도 있는 것 같은데 좀 더 알아봐야 할 듯


참고

Clone this wiki locally