20201011(42Sof Data Validation)

1. 전체 학습시간

오후 02:30 ~ 오후 7:00 (식사, 집안일, 운동 등 시간도 포함돼있음)

2. 학습 목표

42StackOverFLow

3. 학습 방법

하인호와 디스코드

4. 다음 학습 목표

errorClass 적용

5. 상세 학습 내용

class-validator를 사용하여 Request Data에 Validation 적용

  • 모듈 설치
    npm install class-validator --save

  • DTO 파일 생성

import { Min, Max, Length } from "class-validator";

export class Question {

    @Length(1, 20)
    private readonly title: string;

    @Length(1, 5000)
    private readonly text: string;
}
  • 유효성 검사 미들웨어
    CreatePostDto 클래스에서 모든 필드가 필수이며 나머지 속성을 전달하지 않고 일부 속성만 업데이트할 수 있는 HTTP PATCH를 사용하고 있습니다. skipMissingProperties 옵션을 사용하면 상황에 알맞게 사용할 수 있습니다.
import { plainToClass } from 'class-transformer';
import { validate, ValidationError } from 'class-validator';
import * as express from 'express';
import { HttpException } from '../exception/http_exception';

export function validationMiddleware<T>(type: any, skipMissingProperties = false): express.RequestHandler {
    return (req, res, next) => {
        console.log('-----validator------')
        console.log(req.body);
        validate(plainToClass(type, req.body), { skipMissingProperties })
            .then((errors: ValidationError[]) => {
                if (errors.length > 0) {
                    const message = errors.map((error: ValidationError) => {
                        return Object.values(error.constraints)
                    }).join(', ');
                    next(new HttpException(400, message))
                } else
                    next();
            })
    }
}
  • 라우터
    class-validator 패키지를 사용하여 POST 및 PATCH 처리기에서 들어오는 데이터의 유효성을 검사
import express from "express";
import { s3Util } from "../aws/s3_utils";
import { authJwt } from "../middlewares/auth.middleware";
import { QuestionController } from "../controllers/question"
import { AnswerController } from "../controllers/answer";
import { CommentController } from "../controllers/comment";
import { LikeController } from "../controllers/like";
import { Question } from "../controllers/dto/question"
import { Answer } from "../controllers/dto/answer"
import { Comment } from "../controllers/dto/comment"
import { validationMiddleware } from "../middlewares/validation.middleware"

export const postRouter = express.Router();

postRouter.delete('/answer', authJwt, s3Util.s3DeletePhoto, AnswerController.deleteAnswer)
postRouter.post('/answer', authJwt, s3Util.s3ImageUpload({ folder: 'author' }).array("imgFile"), validationMiddleware(Answer, true), AnswerController.uploadAnswer)
postRouter.patch('/answer', authJwt, s3Util.s3ImageUpload({ folder: 'author' }).array("imgFile"), validationMiddleware(Answer), AnswerController.updateAnswer)

postRouter.delete('/question', authJwt, s3Util.s3DeletePhoto, QuestionController.deleteQuestion)
postRouter.post('/question', authJwt, s3Util.s3ImageUpload({ folder: 'author' }).array("imgFile"), validationMiddleware(Question, true), QuestionController.uploadQuestion)
postRouter.patch('/question', authJwt, s3Util.s3ImageUpload({ folder: 'author' }).array("imgFile"), validationMiddleware(Question), QuestionController.updateQuestion)

postRouter.delete('/comment', authJwt, CommentController.deleteComment)
postRouter.post('/comment', authJwt, validationMiddleware(Comment, true), CommentController.uploadComment)
postRouter.patch('/comment', authJwt, validationMiddleware(Comment), CommentController.updateComment)

https://wanago.io/2018/12/17/typescript-express-error-handling-validation/

좋은 웹페이지 즐겨찾기