浏览代码

Implement post 'likes' feature

sbkwgh 8 年之前
父节点
当前提交
97413f1a73
共有 3 个文件被更改,包括 33 次插入1 次删除
  1. 3 1
      models/post.js
  2. 1 0
      models/thread.js
  3. 29 0
      routes/post.js

+ 3 - 1
models/post.js

@@ -34,12 +34,14 @@ module.exports = (sequelize, DataTypes) => {
 				Post.belongsTo(models.User)
 				Post.belongsTo(models.Thread)
 				Post.hasMany(models.Post, { as: 'Replies', foreignKey: 'replyId' })
+				Post.belongsToMany(models.User, { as: 'Likes', through: 'user_post' })
 			},
 			includeOptions () {
 				let models = sequelize.models
 
 				return [
-					{ model: models.User, attributes: ['username', 'createdAt', 'id', 'color'] }, 
+					{ model: models.User, attributes: ['username', 'createdAt', 'id', 'color'] },
+					{ model: models.User, as: 'Likes', attributes: ['username', 'createdAt', 'id', 'color'] },
 					{ model: models.Thread, include: [models.Category]} ,
 					{
 						model: models.Post, as: 'Replies', include:

+ 1 - 0
models/thread.js

@@ -34,6 +34,7 @@ module.exports = (sequelize, DataTypes) => {
 						limit,
 						include: [
 							{ model: models.Thread, attributes: ['slug'] }, 
+							{ model: models.User, as: 'Likes', attributes: ['username', 'createdAt', 'id', 'color'] },
 							{ model: models.User, attributes: ['username', 'createdAt', 'id', 'color'] }, 
 							{
 								model: models.Post, as: 'Replies', include:

+ 29 - 0
routes/post.js

@@ -36,6 +36,35 @@ router.all('*', (req, res, next) => {
 	}
 })
 
+router.put('/:post_id/like', async (req, res) => {
+	try {
+		let post = await Post.findById(req.params.post_id)
+		let user = await User.findOne({ where: { username: req.session.username }})
+		
+		if(!post) throw Errors.invalidParameter('id', 'post does not exist')
+		if(post.UserId === user.id) throw Errors.cannotLikeOwnPost
+
+		await post.addLikes(user)
+
+		res.json({ success: true })
+
+	} catch (e) {
+		if(['invalidParameter', 'cannotLikeOwnPost'].includes(e.name)) {
+			res.status(400)
+			res.json({
+				errors: [e]
+			})
+		} else{
+			console.log(e)
+
+			res.status(500)
+			res.json({
+				errors: [Errors.unknown]
+			})
+		}
+	}
+})
+
 router.post('/', async (req, res) => {
 	let validationErrors = []
 	let thread, replyingToPost, post