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

Use sequelize validations rather than custom ones in router function

sbkwgh преди 8 години
родител
ревизия
656f76859b
променени са 3 файла, в които са добавени 31 реда и са изтрити 47 реда
  1. 17 2
      models/thread.js
  2. 4 24
      routes/thread.js
  3. 10 21
      test/thread_post.js

+ 17 - 2
models/thread.js

@@ -6,7 +6,22 @@ module.exports = (sequelize, DataTypes) => {
 			type: DataTypes.TEXT,
 			set (val) {
 				this.setDataValue('name', val)
-				this.setDataValue('slug', slug(val).toLowerCase())
+				if(val) this.setDataValue('slug', slug(val).toLowerCase())
+			},
+			allowNull: false,
+			validate: {
+				notEmpty: {
+					msg: 'The title cannot be empty'
+				},
+				max: {
+					args: '256',
+					msg: 'The title can only be up to 256 characters'
+				},
+				isString (val) {
+					if(typeof val !== 'string') {
+						throw new sequelize.ValidationError('The title must be a string')
+					}
+				}
 			}
 		},
 		slug: DataTypes.TEXT,
@@ -22,7 +37,7 @@ module.exports = (sequelize, DataTypes) => {
 		instanceMethods: {
 			async getMeta (limit) {
 				let meta = {}
-				
+
 				let posts = this.Posts
 				let firstPost = posts[0]
 				let lastPost = posts.slice(-1)[0]

+ 4 - 24
routes/thread.js

@@ -2,7 +2,7 @@ let express = require('express')
 let router = express.Router()
 
 const Errors = require('../lib/errors.js')
-let { User, Thread, Category, Post } = require('../models')
+let { User, Thread, Category, Post, Sequelize } = require('../models')
 let pagination = require('../lib/pagination.js')
 
 router.get('/:thread_id', async (req, res) => {
@@ -49,27 +49,9 @@ 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 === 0) {
-			validationErrors.push(Errors.missingParameter('name'))
-		}
-
-		if(req.body.category === undefined) {
-			validationErrors.push(Errors.missingParameter('category'))
-		} else if(typeof req.body.category !== 'string') {
-			validationErrors.push(Errors.invalidParameterType('category', 'string'))
-		}
-
-		if(validationErrors.length) throw Errors.VALIDATION_ERROR
-
 		let category = await Category.findOne({ where: {
 			value: req.body.category
 		}})
-
 		if(!category) throw Errors.invalidCategory
 
 		let user = await User.findOne({ where: {
@@ -96,15 +78,13 @@ router.post('/', async (req, res) => {
 		})
 
 	} catch (e) {
-		if(e === Errors.VALIDATION_ERROR) {
+		if(e instanceof Sequelize.ValidationError) {
 			res.status(400)
-			res.json({
-				errors: validationErrors
-			})
+			res.json(e)
 		} else if(e === Errors.invalidCategory) {
 			res.status(400)
 			res.json({
-				errors: [Errors.invalidCategory]
+				errors: [e]
 			})
 		} else {
 			console.log(e)

+ 10 - 21
test/thread_post.js

@@ -122,28 +122,24 @@ describe('Thread and post', () => {
 						category: 'CATEGORY_NAME'
 					})
 
-				res.should.be.json
-				res.should.have.status(401)
-				res.body.errors.should.contain.something.that.deep.equals(Errors.requestNotAuthorized)
 			} catch (res) {
 				res.should.have.status(401)
 				JSON.parse(res.response.text).errors.should.contain.something.that.deep.equals(Errors.requestNotAuthorized)
 			}
 		})
-		it('should return an error if missing parameters', async () => {
+		it('should return an error if missing title', async () => {
 			try {
 				let res = await userAgent
 					.post('/api/v1/thread')
+					.send({
+						category: 'CATEGORY_NAME'
+					})
 
-				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.deep.equals(Errors.missingParameter('category'))
 			} catch (res) {
 				let body = JSON.parse(res.response.text)
+
 				res.should.have.status(400)
-				body.errors.should.contain.something.that.deep.equals(Errors.missingParameter('name'))
-				body.errors.should.contain.something.that.deep.equals(Errors.missingParameter('category'))
+				body.errors.should.contain.something.that.has.property('message', 'name cannot be null')
 			}
 		})
 		it('should return an error if name has no length', done => {
@@ -157,7 +153,7 @@ describe('Thread and post', () => {
 					.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 title cannot be empty')
 
 						done()
 					})
@@ -169,18 +165,14 @@ describe('Thread and post', () => {
 					.set('content-type', 'application/json')
 					.send({
 						name: 123,
-						category: 123
+						category: 'CATEGORY_NAME'
 					})
 
-				res.should.be.json
-				res.should.have.status(400)
-				res.body.errors.should.contain.something.that.deep.equals(Errors.invalidParameterType('name', 'string'))
-				res.body.errors.should.contain.something.that.deep.equals(Errors.invalidParameterType('category', 'string'))
 			} catch (res) {
 				let body = JSON.parse(res.response.text)
+
 				res.should.have.status(400)
-				body.errors.should.contain.something.that.deep.equals(Errors.invalidParameterType('name', 'string'))
-				body.errors.should.contain.something.that.deep.equals(Errors.invalidParameterType('category', 'string'))
+				body.errors.should.contain.something.that.has.property('message', 'The title must be a string')
 			}
 		})
 		it('should return an error if category does not exist', async () => {
@@ -193,9 +185,6 @@ describe('Thread and post', () => {
 						category: 'non-existent'
 					})
 
-				res.should.be.json
-				res.should.have.status(400)
-				res.body.errors.should.contain.something.that.deep.equals(Errors.invalidCategory)
 			} catch (res) {
 				res.should.have.status(400)
 				JSON.parse(res.response.text).errors.should.contain.something.that.deep.equals(Errors.invalidCategory)