Skip to content

Commit

Permalink
Merge pull request #5 from EmergingDigitalAcademy/sequelize-validation
Browse files Browse the repository at this point in the history
added model validation using sequelize
  • Loading branch information
booherbg authored Dec 10, 2024
2 parents 14c1205 + ee2f5c4 commit cd2b439
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 2 deletions.
33 changes: 33 additions & 0 deletions server/middleware/errorHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { ValidationError, DatabaseError, UniqueConstraintError, ForeignKeyConstraintError } from 'sequelize';

export const sequelizeErrorHandler = (error, req, res, next) => {
if (error instanceof ValidationError) {
return res.status(400).json({
error: error.errors.map(e => e.message)
});
}

if (error instanceof UniqueConstraintError) {
return res.status(409).json({
error: 'Resource already exists'
});
}

if (error instanceof ForeignKeyConstraintError) {
return res.status(400).json({
error: 'Invalid reference to related resource'
});
}

if (error instanceof DatabaseError) {
console.error('Database error:', error);
return res.status(500).json({
error: 'A database error occurred'
});
}

console.error('Unexpected error:', error);
res.status(500).json({
error: 'An unexpected error occurred'
});
};
21 changes: 19 additions & 2 deletions server/models/todo.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,28 @@ Todo.init({
},
name: {
type: DataTypes.STRING,
allowNull: false
allowNull: false,
validate: {
notNull: {
msg: 'name is required'
},
notEmpty: {
msg: 'name cannot be empty'
}
}
},
priority: {
type: DataTypes.ENUM('low', 'medium', 'high'),
allowNull: false
allowNull: false,
validate: {
notNull: {
msg: 'priority is required'
},
isIn: {
args: [['low', 'medium', 'high']],
msg: 'priority must be low, medium, or high'
}
}
},
due_date: {
type: DataTypes.DATE,
Expand Down
5 changes: 5 additions & 0 deletions server/routes/todos.router.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import express from 'express';
import Todo from '../models/todo.js';
import validateTodo from '../middleware/todoValidation.js';
import { rejectUnauthenticated } from '../middleware/auth.js';
import { sequelizeErrorHandler } from '../middleware/errorHandler.js';

const router = express.Router();

Expand Down Expand Up @@ -122,4 +123,8 @@ router.delete('/:id', async (req, res) => {
}
});

// Add at the end of your router
router.use(sequelizeErrorHandler);


export default router;

0 comments on commit cd2b439

Please sign in to comment.