Kaynağa Gözat

Get comments for user by passing comments query to route

sbkwgh 8 yıl önce
ebeveyn
işleme
1ec8bf1085
3 değiştirilmiş dosya ile 55 ekleme ve 2 silme
  1. 6 0
      models/user.js
  2. 11 2
      routes/user.js
  3. 38 0
      test/user.js

+ 6 - 0
models/user.js

@@ -17,6 +17,12 @@ module.exports = (sequelize, DataTypes) => {
 			type: DataTypes.BOOLEAN,
 			defaultValue: false
 		}
+	}, {
+		classMethods: {
+			associate (models) {
+				User.hasMany(models.Post)
+			}
+		}
 	})
 
 	return User

+ 11 - 2
routes/user.js

@@ -119,10 +119,19 @@ router.post('/', async (req, res) => {
 
 router.get('/:username', async (req, res) => {
 	try {
-		let user = await User.findOne({
+		let queryObj = {
 			attributes: { exclude: ['hash', 'id'] },
 			where: { username: req.params.username }
-		})
+		}
+
+		if(req.query.posts) {
+			queryObj.include = [{
+				model: Models.Post,
+				include: Models.Post.includeOptions()
+			}]
+		}
+
+		let user = await User.findOne(queryObj)
 
 		if(!user) throw Errors.accountDoesNotExist
 

+ 38 - 0
test/user.js

@@ -292,6 +292,44 @@ describe('User', () => {
 				body.errors.should.contain.something.that.deep.equals(Errors.accountDoesNotExist)
 			}
 		})
+
+		it('should get posts as well if posts query is appended', async () => {
+			let agent = chai.request.agent(server)
+
+			await agent
+				.post('/api/v1/user/adminaccount/login')
+				.set('content-type', 'application/x-www-form-urlencoded')
+				.send({ password: 'password' })
+
+			await agent
+				.post('/api/v1/category')
+				.set('content-type', 'application/x-www-form-urlencoded')
+				.send({ name: 'categorynamehere' })
+
+			await agent
+				.post('/api/v1/thread')
+				.set('content-type', 'application/x-www-form-urlencoded')
+				.send({ name: 'a thread name', category: 'categorynamehere' })
+
+			await agent
+				.post('/api/v1/post')
+				.set('content-type', 'application/json')
+				.send({ threadId: 1, content: 'content for post' })
+
+			await agent
+				.post('/api/v1/post')
+				.set('content-type', 'application/json')
+				.send({ threadId: 1, content: 'content for another post' })
+
+			let res = await agent
+				.get('/api/v1/user/adminaccount?posts=true')
+
+			res.should.be.json
+			res.should.have.status(200)
+			res.body.should.have.property('username', 'adminaccount')
+			res.body.should.have.property('Posts')
+			res.body.Posts.should.have.property('length', 2)
+		})
 	})
 
 	describe('/:username/login POST user', () => {