Преглед на файлове

Use sequelize validation for category model and routes

sbkwgh преди 8 години
родител
ревизия
a54fa9fa0e
променени са 3 файла, в които са добавени 30 реда и са изтрити 26 реда
  1. 20 4
      models/category.js
  2. 7 19
      routes/category.js
  3. 3 3
      test/category.js

+ 20 - 4
models/category.js

@@ -5,10 +5,16 @@ module.exports = (sequelize, DataTypes) => {
 		name: {
 			type: DataTypes.STRING,
 			unique: true,
-			set (val) {
-				let underscored = val.trim().replace(/\s/g, '_').toUpperCase()
-				this.setDataValue('name', val)
-				this.setDataValue('value', underscored)
+			allowNull: false,
+			validate: {
+				notEmpty: {
+					msg: 'The category name can\'t be empty'
+				},
+				isString (val) {
+					if(typeof val !== 'string') {
+						throw new sequelize.ValidationError('The category name must be a string')
+					}
+				}
 			}
 		},
 		value: {
@@ -22,6 +28,16 @@ module.exports = (sequelize, DataTypes) => {
 			}
 		}
 	}, {
+		hooks: {
+			beforeCreate (category) {
+				if(!category.name) {
+					throw new sequelize.ValidationError('The category name cant\'t be empty')
+				} else {
+					let underscored = category.name.trim().replace(/\s/g, '_').toUpperCase()
+					category.value = underscored
+				}
+			}
+		},
 		classMethods: {
 			associate (models) {
 				Category.hasMany(models.Thread)

+ 7 - 19
routes/category.js

@@ -3,7 +3,7 @@ let router = express.Router()
 
 const Errors = require('../lib/errors')
 let pagination = require('../lib/pagination')
-let { Category, Post, Thread, User } = require('../models')
+let { Category, Post, Thread, User, Sequelize } = require('../models')
 
 router.get('/', async (req, res) => {
 	try {
@@ -147,36 +147,24 @@ router.all('*', (req, res, next) => {
 })
 
 router.post('/', async (req, res) => {
-	let validationErrors = []
-
 	try {
-		if(req.body.name === undefined) {
-			validationErrors.push(Errors.missingParameter('name'))
-		} else if(typeof req.body.name !== 'string') {
-			validationErrors.push(Errors.invalidParameterType('name', 'string'))
-		} else if(!req.body.name.length) {
-			validationErrors.push(Errors.missingParameter('name'))
-		}
-
-		if(validationErrors.length) throw Errors.VALIDAITON_ERROR
-
 		let category = await Category.create({
 			name: req.body.name
 		})
 
 		res.json(category.toJSON())
 	} catch (e) {
-		if(e === Errors.VALIDAITON_ERROR) {
-			res.status(400)
-			res.json({
-				errors: validationErrors
-			})
-		} else if(e.name === 'SequelizeUniqueConstraintError') {
+		if(e.name === 'SequelizeUniqueConstraintError') {
 			res.status(400)
 			res.json({
 				errors: [Errors.categoryAlreadyExists]
 			})
+		} else if(e instanceof Sequelize.ValidationError) {
+			res.status(400)
+			res.json(e)
 		} else {
+			console.log(e)
+
 			res.status(500)
 			res.json({
 				errors: [Errors.unknown]

+ 3 - 3
test/category.js

@@ -80,7 +80,7 @@ describe('Category', () => {
 				res.body.errors.should.contain.something.that.deep.equals(Errors.categoryAlreadyExists)
 			} catch (res) {
 				res.should.have.status(400)
-				JSON.parse(res.response.text).errors.should.contain.something.that.deep.equals(Errors.categoryAlreadyExists)
+				res.response.body.errors.should.contain.something.that.deep.equals(Errors.categoryAlreadyExists)
 			}
 		})
 		it('should return an error if missing category parameter', done => {
@@ -91,7 +91,7 @@ describe('Category', () => {
 				.end((err, res) => {
 					res.should.be.json
 					res.should.have.status(400)
-					res.body.errors.should.contain.something.that.deep.equals(Errors.missingParameter('name'))
+					res.body.errors.should.contain.something.that.has.property('message', 'name cannot be null')
 
 					done()
 				})
@@ -104,7 +104,7 @@ describe('Category', () => {
 				.end((err, res) => {
 					res.should.be.json
 					res.should.have.status(400)
-					res.body.errors.should.contain.something.that.deep.equals(Errors.missingParameter('name'))
+					res.body.errors.should.contain.something.that.has.property('message', 'The category name can\'t be empty')
 
 					done()
 				})