Skip to content

Validation

๋ฐ•์ง€์œจ edited this page Oct 16, 2021 · 2 revisions
์ž‘์„ฑ์ž ์ž‘์„ฑ์ผ์‹œ
earthkingman 2021-10-16

  • ๋ชจ๋“ˆ ์„ค์น˜ 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/