Swagger - boostcamp-2020/Project03-A-TOTP GitHub Wiki

๋ฐฐ๊ฒฝ

๊ฐœ๋ฐœ์ด ๋ฐ”๋น ์„œ 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);

์ž‘์„ฑํ•˜๋ฉด ์ฃผ์„์ด ๊ต‰์žฅํžˆ ๊ธธ์–ด์ง„๋‹ค. ์Šคํ‚ค๋งˆ๋ฅผ ๋ฏธ๋ฆฌ ์ •์˜ํ•ด๋†“์„ ์ˆ˜๋„ ์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ ์ข€ ๋” ์•Œ์•„๋ด์•ผ ํ•  ๋“ฏ

์ฐธ๊ณ