반응형
  • 저번에 Swagger 사용하기 1에서 간단한 로그인 기능을 만들어 봄 ( DB 사용 X )
  • 회원가입 기능을 추가하면서 코드를 분리하고 components를 사용해 봄

회원가입 기능 추가

  • 이런 식으로 하면 서버를 다시 시작했을 때, 새로 가입한 user 정보들은 날아가긴 하지만 swagger 사용이 주 목적임으로 최대한 간단하게 함
// 회원가입 기능을 추가한 routes/user.js
var router = require('express').Router();
var users = [
    {id: 'chb2005', pw: '1234', nickname: 'changbum'},
    {id: 'alex123', pw: 'a789', nickname: 'alex'},
    {id: 'h1997', pw:'h456!@#', nickname: 'Harry'},
];

router.post('/nickname', async (req, res, next) => {
    try {
        for(var i = 0; i < users.length; i++) {
            if(req.body.id == users[i].id) {
                if(req.body.pw == users[i].pw) {
                    return res.status(200).json({
                        message: '닉네임 : ' + users[i].nickname,
                    });
                } else {
                    return res.status(401).json({
                        message: '비밀번호가 틀렸습니다!',
                    });
                }
            }
        }
        return res.status(401).json({
            messge: '아이디가 존재하지 않습니다!',
        });
    } catch(err) {
        console.log(err);
        return next(err);
    }
});

router.post('/signup', async (req, res, next) => {
    try {
        for(var i = 0; i < users.length; i++) {
            if(req.body.id == users[i].id) {
                if(req.body.pw == users[i].pw) {
                    return res.status(401).json({
                        message: '아이디가 중복됩니다!',
                    });
                }
            }
        }
        users.push({id: req.body.id, pw: req.body.pw, nickname: req.body.nickname});
        return res.status(200).json({
            messge: '회원가입 완료!',
        });
    } catch(err) {
        console.log(err);
        return next(err);
    }
});

module.exports = router;

user.yaml

  • swagger 폴더 생성 후 user.yaml 이라는 파일을 생성
  • 전에 user.js에 써줬던 Swagger 관련 코드를 user.yaml 파일에 옮김으로서 코드를 더 깔끔하게 할 수 있음
// user.yaml
paths:
 /user/nickname:
  post:
   tags:
   - user
   description: 닉네임 조회
   parameters:
   - in: body
     name: body
     required: true
     schema:
      properties:
       id:
        type: string
       pw:
        type: string
   responses:
    200:
     description: 닉네임 조회 성공
     schema:
      properties:
       message:
        type: string
    401:
     description: 닉네임 조회 실패
     schema:
      properties:
       message:
        type: string
 /user/signup:
  post:
   tags:
    - user
   description: 회원가입
   parameters:
    - in: body
      name: body
      required: true
      schema:
       properties:
        id:
         type: string
        pw:
         type: string
        nickname:
         type: string
   responses:
    200:
     description: 회원가입 성공
     schema:
      properties:
       message:
        type: string
    401:
     description: 회원가입 실패
     schema:
      properties:
       message:
        type: string

components 사용

  • 위와 같이 코드를 작성했을 때 모든 Response 값은 String 타입인 message로 동일한데, 똑같은 걸 4번이나 쓰는것을 확인 할 수 있음
  • 다음과 같이 'components'를 추가함으로서 이를 줄일 수 있음
// 수정된 user.yaml
components:
 schemas:
  Res:
   properties:
    message:
     type: string
     description: 메세지


paths:
 /user/nickname:
  post:
   tags:
    - user
   description: 닉네임 조회
   parameters:
    - in: body
      name: body
      required: true
      schema:
       properties:
        id:
         type: string
        pw:
         type: string
   responses:
    200:
     description: 닉네임 조회 성공
     schema:
      $ref: '#/components/schemas/Res'
    401:
     description: 닉네임 조회 실패
     schema:
      $ref: '#/components/schemas/Res'
 /user/signup:
  post:
   tags:
    - user
   description: 회원가입
   parameters:
    - in: body
      name: body
      required: true
      schema:
       properties:
        id:
         type: string
        pw:
         type: string
        nickname:
         type: string
   responses:
    200:
     description: 회원가입 성공
     schema:
      $ref: '#/components/schemas/Res'
    401:
     description: 회원가입 실패
     schema:
      $ref: '#/components/schemas/Res'
  • 이렇게 하면 코드도 간단해지고 schema를 볼 때도 편해짐
  • 만약 더 복잡한 프로젝트를 할 때, response 뿐만 아니라, 예를 들어 user의 schema를 components에 써주고 계속 사용한다는 식으로 사용하면 매우 유용
  • 그리고 이를 적용시키기 위해서 swagger.js에서 options를 다음과 같이 수정
const options = {
    swaggerDefinition: {
        components: {},
        info: {
            title: 'Test API',
            version: '1.0.0',
            description: 'Test API with express',
        },
        host: 'localhost:52273',
        basePath: '/'
    },
    apis: ['./routes/*.js', './swagger/*'],
};

결과

  • signup 페이지가 생긴 것을 확인 가능

  • 새로운 id와 pw 입력

  • id가 존재하지 않음

  • 아까 입력했던 id와 pw로 회원가입 진행

  • 회원가입 완료

  • 방금 가입했던 id, pw로 로그인 하면 새로 가입한 nickname이 return 됨을 확인

반응형

↓ 클릭시 이동

복사했습니다!