Skip to content

Commit

Permalink
feature(view comments): add view comments
Browse files Browse the repository at this point in the history
- add view comments functionality
- add view comments test
- add swagger documentation of the feature

[Starts #170766760]
  • Loading branch information
erickyvand committed Jan 23, 2020
1 parent a3d6dde commit f5a48ff
Show file tree
Hide file tree
Showing 6 changed files with 209 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/controllers/comment.controller.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import CommentService from '../services/comment.service';
import ResponseService from '../services/response.service';
import { paginationHelper } from '../helpers';

/**
* class
Expand All @@ -25,7 +26,6 @@ class CommentController {
return ResponseService.send(res);
}


/**
*
*
Expand All @@ -41,6 +41,36 @@ class CommentController {
ResponseService.setSuccess(200, 'Comment was deleted successfully');
return ResponseService.send(res);
}

/**
*
*
* @static
* @param {req} req
* @param {res} res
* @returns {object} This function returns list of comments posted on thread
* @memberof CommentController
*/
static async viewCommentPostedOnTripRequest(req, res) {
const { page, limit } = req.query;
const offset = (page - 1) * limit;
const results = await CommentService
.findByPropertyAndCountAll({
userId: req.userData.id,
subjectId: req.params.tripId
},
{
offset,
limit
});
ResponseService.setSuccess(200, 'List all comments', {
pageMeta: paginationHelper({
count: results.count, rows: results.rows, offset, limit
}),
rows: results.rows
});
return ResponseService.send(res);
}
}

export default CommentController;
1 change: 1 addition & 0 deletions src/routes/trip.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ router.get('/requests', authMiddleware.checkUserLoggedIn, requestValidation, Tri
router.get('/locations', authMiddleware.checkUserLoggedIn, TripController.viewAvailableLocations);
router.post('/requests/:tripId/comments', authMiddleware.checkUserLoggedIn, UserValidation.validateUserComment, CommentController.addCommentOnTripRequest); // user comment on request trip route
router.delete('/:tripId/comments/:commentId', authMiddleware.checkUserLoggedIn, UserValidation.validateDeleteTripComment, TripMiddleware.checkTripExist, CommentMiddleware.checkCommentExist, CommentController.deleteComment); // user deletes comment route
router.get('/request/:tripId/comments', authMiddleware.checkUserLoggedIn, UserValidation.validateViewComment, CommentController.viewCommentPostedOnTripRequest); // user view comment posted on the thread

export default router;
21 changes: 21 additions & 0 deletions src/services/comment.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,27 @@ class CommentService {
where: property,
});
}

/**
* A method to querry with condition
* and count all records
* @static
* @param {object} property - The condion as an object
* @param {number} offset - The offset to be used
* @param {number} limit - The limit to be used
* @returns {number} The data retrieved
* @memberof TripService
*/
static findByPropertyAndCountAll(property, { offset, limit }) {
return Comments.findAndCountAll({
where: property,
order: [
['id', 'DESC']
],
offset,
limit
});
}
}

export default CommentService;
42 changes: 42 additions & 0 deletions src/swagger/trip.swagger.js
Original file line number Diff line number Diff line change
Expand Up @@ -409,3 +409,45 @@
* description: Trip ID doesn't exists, Comment ID doesn't exists
*
*/

/**
* @swagger
* /api/trips/request/{tripId}/comments:
* get:
* tags:
* - trips
* name: View all comments
* summary: User should be able to view his comments posted on requested trip
* produces:
* - application/json
* consumes:
* - application/json
* parameters:
* - in: header
* name: Authorization
* required: true
* type: string
* - in: path
* name: tripId
* - name: page
* in: query
* type: integer
* - name: limit
* in: query
* type: integer
* schema:
* $ref: '#/definitions/viewComments'
* type: object
* responses:
* '200':
* description: List all comments
* '400':
* description: Page must be greater than 0,
* Limit must be a number,
* Page must be a number,
* Page is required,
* Limit is required
* '404':
* description: Not comments found for you
*
*/
61 changes: 61 additions & 0 deletions src/tests/trip/view-comments.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import chai from 'chai';
import chaiHttp from 'chai-http';
import app from '../../app';
import { loggedInToken, userWithNoTripToken } from '../fixtures/users.fixture';
import { createTrip } from '../fixtures/trip.fixture';
import { badRequest } from '../fixtures/comments.fixture';

chai.should();
chai.use(chaiHttp);

describe('/Get view comments posted on trips requests', () => {
let trip;
before(async () => {
trip = await createTrip();
});
it('Should get comments posted on trip requests', (done) => {
chai.request(app)
.get(`/api/trips/request/${trip.id}/comments?page=1&limit=1`)
.set('Authorization', loggedInToken)
.end((err, res) => {
res.body.should.be.an('object');
res.status.should.be.equal(200);
res.body.data.should.have.property('pageMeta');
res.body.data.should.have.property('rows');
res.body.data.rows.should.be.an('array');
res.body.data.rows[0].should.have.property('id');
res.body.data.rows[0].should.have.property('userId');
res.body.data.rows[0].should.have.property('subjectId');
res.body.data.rows[0].should.have.property('subjectType');
res.body.data.rows[0].should.have.property('comment');
res.body.data.rows[0].should.have.property('createdAt');
res.body.data.rows[0].should.have.property('updatedAt');
res.body.should.have.property('message').equal('List all comments');
done();
});
});

it('Should not allow invalid parameters passed in the route', (done) => {
chai.request(app)
.get(`/api/trips/request/${badRequest}/comments?page=1&limit=1`)
.set('Authorization', loggedInToken)
.end((err, res) => {
res.body.should.be.an('object');
res.status.should.be.equal(400);
res.body.should.have.property('message');
done();
});
});

it('Should not show requested trip comments when no comment found or does not belong to the trip', (done) => {
chai.request(app)
.get(`/api/trips/request/${trip.id}/comments?page=1&limit=1`)
.set('Authorization', userWithNoTripToken)
.end((err, res) => {
res.body.should.be.an('object');
res.status.should.be.equal(404);
res.body.should.have.property('message').equal('Comments not found or does not belong to this trip');
done();
});
});
});
53 changes: 53 additions & 0 deletions src/validations/user.validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import ResponseService from '../services/response.service';
import JwtService from '../services/jwt.service';
import UserService from '../services/user.service';
import TripService from '../services/trip.service';
import CommentService from '../services/comment.service';

/**
* class for validations
Expand Down Expand Up @@ -179,6 +180,58 @@ class UserValidation {
}
next();
}

/**
*
*
* @static
* @param {req} req
* @param {res} res
* @param {next} next
* @returns {validation} This function validate view comments route
* @memberof UserValidation
*/
static async validateViewComment(req, res, next) {
const page = parseInt(req.query.page, 10);
const limit = parseInt(req.query.limit, 10);

const schema = Joi.object({
tripId: Joi.number().greater(0).required(),
page: Joi.number().greater(0).required()
.messages({
'number.greater': 'Page must be greater than 0',
'object.unknown': `${page} is not allowed`,
'any.required': 'Page is required',
'number.base': 'Page must be a number'
}),
limit: Joi.number().greater(0).required()
.messages({
'number.greater': 'Limit must be greater than 0',
'object.unknown': `${limit} is not allowed`,
'any.required': 'Limit is required',
'number.base': 'Limit must be a number'
})
}).options({ abortEarly: false });

const { error } = schema.validate({ ...req.params, ...req.query });
if (error) {
const { details } = error;
const errors = details.map(({ message }) => message.replace(/[^a-zA-Z0-9 .-]/g, ''));
ResponseService.setError(400, errors);
return ResponseService.send(res);
}

const comment = await CommentService.findCommentByProperty({
userId: req.userData.id,
subjectId: req.params.tripId
});

if (!comment) {
ResponseService.setError(404, 'Comments not found or does not belong to this trip');
return ResponseService.send(res);
}
next();
}
}

export default UserValidation;

0 comments on commit f5a48ff

Please sign in to comment.