express 유효성 검사 방법 [ express-validator ]

2022. 5. 23. 15:03Node.js, Express

개발을 진행 할 때 if문 범벅이 되어서 코드 작성이 가독성이 떨어진다.

express-validator는 if문 범벅 유효성 검사를 아주 간단하게 유효성 검사를 도와주는 라이브러리다

 

if문 범벅 예시

 if (!index || !stageCheck || !playTime) {
      console.log('데이터가 없습니다. 1')
    } else if (
      typeof index !== 'number' ||
      typeof stageCheck !== 'string' ||
      typeof playTime !== 'number' 
    ) {
      console.log('타입 형식을 맞춰주세요, 2')
    }

express-validator 사용 시

const { validationResult, body } = require('express-validator')

const Index = body('index').notEmpty().isNumeric()
const StageCheck = body('stageCheck').notEmpty().isString()
const PlayTime = body('playTime').notEmpty().isNumeric()

 

express-validator 설치

npm i express-validator

 

사용방법

const express = require('express')
const router = express.Router()
// validationResult = 유효성 검사가 통과 하지 못한 에러 목록
const { validationResult, body } = require('express-validator')
const httpError = require('http-errors')
const { Service } = require('./test2')

// 에러 발생 확인 함수 => 에러 발생시 400 에러 발생
const Validator = (req, res, next) => {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    throw httpError(400)
  }
  next()
}

const Index = body('index').notEmpty().isNumeric()
// 의미 : body에 들어오는 index 변수는 비어있으면 안되고 Number형 이어야 한다.
const StageCheck = body('stageCheck').notEmpty().isString()
// 의미 : body에 들어오는 stageCheck 변수는 비어있으면 안되고 String형 이어야 한다.
const PlayTime = body('playTime').notEmpty().isNumeric()
// 의미 : body에 들어오는 stageCheck 변수는 비어있으면 안되고 Number형 이어야 한다.

// router.post('경로',[유효성 검사], 서비스 함수)
// Validator 에러 발생 확인 함수는 배열 마지막에 넣어준다.

router.post('/', [Index, StageCheck, PlayTime, Validator], Service)

 

express-validator에서 유효검사 데이터 타입은 여러개 있으니 문서에서 확인!

 

express-validator 문서 : https://express-validator.github.io/docs/

728x90
반응형