Skip to content

Commit

Permalink
feat: 모델 인스턴스 validation 공통 처리
Browse files Browse the repository at this point in the history
  • Loading branch information
Aleph-Kim committed Aug 29, 2024
1 parent 04c0a3b commit de9b857
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 37 deletions.
4 changes: 4 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const PORT = 3000;
const quoteRoutes = require('./routes/quoteRoutes');

const sequelize = require('./config/db')
const beforeValidateHandler = require('./middlewares/beforeValidateHandler');

const quoteModel = require('./models/quote')

const notFoundHandler = require('./middlewares/notFoundHandler');
Expand All @@ -28,6 +30,8 @@ app.use(notFoundHandler);
// 에러 핸들링 미들웨어
app.use(errorHandler);

beforeValidateHandler(sequelize);

// 데이터베이스 동기화 및 서버 시작
sequelize.sync({ alter: true }).then(() => {
console.info('Database & tables 생성');
Expand Down
31 changes: 31 additions & 0 deletions src/middlewares/beforeValidateHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const { ValidationError } = require('sequelize');

/**
* 모델 인스턴스 validation
*
* @param {Object} entity - 검증할 모델 인스턴스
* @throws {ValidationError} 속성 규칙에 따라 필드 값이 유효하지 않은 경우 예외 발생
*/
function validateAttributes(entity) {
for (const field in entity.rawAttributes) {
const inputValue = entity[field];
const column = entity.rawAttributes[field];
// 컬럼이 null을 허용하지 않고 입력받은 값이 비어있을 경우
if (column.allowNull === false && !inputValue) {
throw new ValidationError(`Validation error: ${column.comment}을(를) 입력해주세요.`);
}
}
}

/**
* beforeValidate 핸들러 등록
*
* @param {Object} sequelize - Sequelize 인스턴스
*/
function registerBeforeValidateHook(sequelize) {
sequelize.addHook('beforeValidate', (entity, options) => {
validateAttributes(entity);
});
}

module.exports = registerBeforeValidateHook;
61 changes: 33 additions & 28 deletions src/models/quote.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,40 @@ const sequelize = require('../config/db');
* 명언 객체
*/
const quoteModel = sequelize.define('quote', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
body: {
type: DataTypes.STRING,
allowNull: false,
comment: "명언 내용"
},
author: {
type: DataTypes.STRING,
allowNull: false,
comment: "명언을 남긴 사람"
},
authorProfile: {
type: DataTypes.STRING,
comment: "명언을 남긴 사람에 대한 설명"
},
category: {
type: DataTypes.ENUM,
values: ['인생', '성공', '동기부여', '사랑', '지혜', '개발'],
allowNull: false,
comment: "명언의 카테고리"
}
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
body: {
type: DataTypes.STRING,
allowNull: false,
comment: "명언 내용"
},
author: {
type: DataTypes.STRING,
allowNull: false,
comment: "명언을 남긴 사람"
},
authorProfile: {
type: DataTypes.STRING,
comment: "명언을 남긴 사람에 대한 설명"
},
category: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isIn: {
args: [['인생', '성공', '동기부여', '사랑', '지혜', '개발']],
msg: "올바른 카테고리를 입력해주세요."
}
},
comment: "명언의 카테고리"
}
}, {
timestamps: true,
createdAt: "create_date",
modifiedAt: "modify_date",
timestamps: true,
createdAt: "create_date",
updatedAt: "update_date",
});

module.exports = quoteModel;
9 changes: 0 additions & 9 deletions src/services/quoteService.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,6 @@ class QuoteService {
* @returns quote 객체
*/
async createQuote(data) {
switch (true) {
case !data.body:
throw new Error("명언 내용을 입력해주세요.");
case !data.author:
throw new Error("작성자를 입력해주세요.");
case !data.category:
throw new Error("카테고리를 선택해주세요.");
}

const quote = await quoteModel.create(data);
return quote;
}
Expand Down

0 comments on commit de9b857

Please sign in to comment.