Jelajahi Sumber

Fix test, implement tests for report routes

sbkwgh 8 tahun lalu
induk
melakukan
21068b039e
2 mengubah file dengan 64 tambahan dan 7 penghapusan
  1. 60 3
      routes/report.js
  2. 4 4
      test/report.js

+ 60 - 3
routes/report.js

@@ -1,7 +1,7 @@
 let express = require('express')
 let router = express.Router()
 
-let { User, Post, Report } = require('../models')
+let { User, Post, Report, Sequelize } = require('../models')
 const Errors = require('../lib/errors')
 
 router.all('*', (req, res, next) => {
@@ -14,7 +14,46 @@ router.all('*', (req, res, next) => {
 		})
 	}
 })
-router.post('/', async (req, res) => {})
+router.post('/', async (req, res) => {
+	try {
+		let post = await Post.findById(req.body.postId)
+
+		if(!post) {
+			throw new Sequelize.ValidationError('Post id is not valid', [
+				new Sequelize.ValidationErrorItem(
+					'Post id is not valid',
+					'Validation error',
+					'postId',
+					req.body.postId
+				)
+			])
+		}
+
+		let user = await User.findOne({
+			where: { username: req.session.username }
+		})
+
+		let report = await Report.create({ reason: req.body.reason })
+		report.setFlaggedByUser(user)
+		report.setPost(post)
+
+		res.json({
+			success: true
+		})
+	} catch (e) {
+		if(e instanceof Sequelize.ValidationError) {
+			res.status(400)
+			res.json(e)
+		} else {
+			console.log(e)
+
+			res.status(500)
+			res.json({
+				errors: [Errors.unknown]
+			})
+		}
+	}
+})
 
 router.all('*', (req, res, next) => {
 	if(req.session.admin) {
@@ -26,6 +65,24 @@ router.all('*', (req, res, next) => {
 		})
 	}
 })
-router.get('/', async (req, res) => {})
+router.get('/', async (req, res) => {
+	try {
+		let reports = await Report.findAll({
+			include: [
+				{model: User, as: 'FlaggedByUser' },
+				{ model: Post, include: Post.includeOptions() }
+			]
+		})
+
+		res.json(reports)
+	} catch (e) {
+		console.log(e)
+
+		res.status(500)
+		res.json({
+			errors: [Errors.unknown]
+		})
+	}
+})
 
 module.exports = router

+ 4 - 4
test/report.js

@@ -154,7 +154,7 @@ describe('Report', () => {
 	describe('GET /report', () => {
 		before(async () => {
 			await Report.destroy({
-				where: { id: 1 }
+				where: {}
 			})
 
 			let report1 = await Report.create({ reason: 'spam' })
@@ -182,9 +182,9 @@ describe('Report', () => {
 			res.should.be.json
 
 			res.body.should.have.length(2)
-			res.body[0].should.have.deep.property('User.username', 'useraccount')
-			res.body[0].should.have.deep.property('Post.id', 1)
-			res.body[0].should.have.property('reason', 'spam')
+			res.body.should.contain.something.with.deep.property('FlaggedByUser.username', 'useraccount')
+			res.body.should.contain.something.with.deep.property('reason', 'spam')
+			res.body.should.contain.something.with.deep.property('reason', 'inappropriate')
 		})
 
 		it('should return an error if not admin account', done => {