저번 포스트에서는 유저 인증 미들웨어를 작성했었다.
이번 포스트에서는 express-validator를 사용한 게시글 관리 미들웨어를 작성할 것이다.
1. express-validator란?
공식문서 : https://express-validator.github.io/docs/
express-validator는 Node.js/Express 앱에서 입력값을 검증하고 정리하기 위해 사용되는 미들웨어 라이브러리다. 이 버전의 express-validator를 사용하려면 애플리케이션이 Node.js 14 이상, express.js 4.x 여야한다.
자세한 사용법과 어떻게 활용하는지는 링크를 참고하길 바란다.
2. 게시글 관리 미들웨어
캡스톤 프로젝트에 쓸 게시글 관리 기능에 추가할 미들웨어를 작성했다.
농부와 근로자가 작성할 수 있는 게시글이 서로 다르기 때문에 나눠줬다.
로그인이 되어있는지 확인하는 로직은 중복되기 때문에 handleValidationAndAuth 함수로 따로 빼줬다.
생성, 업데이트 라우터에 추가했고 업데이트에는 서비스 클래스에서 따로 인증 로직을 추가해줬다.
// 로그인 되어있는지 확인
const handleValidationAndAuth = (req, res, next) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
if (!req.user || !req.user.username) {
return res.status(401).json({ message: "로그인 해주세요." })
}
next()
}
// 농부 게시글
export const validateFarmerBoard = [
body("title").notEmpty().withMessage("제목을 입력해주세요."),
body("content").notEmpty().withMessage("내용을 입력해주세요."),
body("location").notEmpty().withMessage("위치를 입력해주세요."),
body("work").notEmpty().withMessage("업무를 입력해주세요."),
body("date").notEmpty().withMessage("날짜와 시간을 입력해주세요."),
body("charge").notEmpty().withMessage("급여를 입력해주세요."),
handleValidationAndAuth,
(req, res, next) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
next()
},
]
// 근로자 게시글
export const validateWorkerBoard = [
body("title").notEmpty().withMessage("제목을 입력해주세요."),
body("content").notEmpty().withMessage("내용을 입력해주세요."),
handleValidationAndAuth,
(req, res, next) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
next()
},
]
export default {
validateFarmerBoard,
validateWorkerBoard,
}

감사합니다 (๑•̀ㅂ•́)و✧
'Development > Back-end' 카테고리의 다른 글
| [Express] 알리고 API를 사용한 로그인/회원가입 구현하기 (0) | 2025.06.02 |
|---|---|
| [Express] 알리고 API 를 이용한 문자 서비스 예제 (0) | 2025.05.19 |
| [Express] 유저 인증 미들웨어 (0) | 2025.05.07 |
| [Back-end] JWT(JSON Web Token) (0) | 2025.03.14 |
| [Spring Boot] 간단한 게시글 CRUD (0) | 2025.02.26 |