Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"main": "src/server.ts",
"dependencies": {
"@types/bcrypt": "^3.0.0",
"@types/lodash": "^4.14.168",
"bcrypt": "^3.0.8",
"body-parser": "^1.19.0",
"class-transformer": "^0.2.3",
Expand All @@ -14,6 +15,7 @@
"envalid": "^6.0.1",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
"mongoose": "^5.8.11"
},
"devDependencies": {
Expand Down
124 changes: 124 additions & 0 deletions server/src/controllers/comments.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { Router, Request, Response, NextFunction } from 'express';
import Controller from '../interfaces/controller.interface';
import authMiddleware from '../middleware/auth.middleware';
import restaurantModel from '../models/restaurant.model';
import RestaurantNotFoundException from '../exceptions/RestaurantNotFoundException';
import validationMiddleware from '../middleware/validation.middleware';
import WrongCredentialsException from '../exceptions/WrongCredentialsException';
import commentsModel from '../models/comments.model';
import CreateCommentDto from '../dto/comment.dto';
import userModel from '../models/user.model';
import RequestWithUser from '../interfaces/requestWithUser.interface';
import CommentIsNotExist from '../exceptions/CommentIsNotExist';
import CommentTooShort from '../exceptions/CommentTooShort';
import permissionMiddleware from '../middleware/permission.middleware';
import commentDeleteMiddleware from '../middleware/commentDelete.middleware';
import commentEditMiddleware from '../middleware/editComment.middleware';

class CommentsController implements Controller {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a lot of code that we have to test.

public path = '/comments';
public router = Router();
private restaurant = restaurantModel;
private comment = commentsModel;
private user = userModel;

constructor() {
this.initializeRoutes();
}

private initializeRoutes() {
this.router.get(`${this.path}`, authMiddleware, permissionMiddleware, this.getComments);
this.router.get(`${this.path}/:id`, authMiddleware, permissionMiddleware, this.getCommentsById);
this.router.put(
`${this.path}/:restaurantId`,
authMiddleware,
validationMiddleware(CreateCommentDto),
this.createComment
);
this.router.patch(`${this.path}/:id`, authMiddleware, commentEditMiddleware, this.editComment);
this.router.delete(`${this.path}/:id`, authMiddleware, commentDeleteMiddleware, this.deleteComment);
}

private getComments = async (request: Request, response: Response, next: NextFunction) => {
const comments = await this.comment.find();
comments ? response.send(comments) : next(new CommentIsNotExist());
};

private getCommentsById = async (request: Request, response: Response, next: NextFunction) => {
const id = request.params.id;
try {
const comment = await this.comment.findById(id).populate('restaurant', 'name').populate('user', 'lastName');
comment ? response.send(comment) : next(new CommentIsNotExist());
} catch {
next(new CommentIsNotExist());
}
};

private createComment = async (request: RequestWithUser, response: Response, next: NextFunction) => {
try {
const restaurantId: string = request.params.restaurantId;
if (!restaurantId) {
return next(new RestaurantNotFoundException(restaurantId));
}

const restaurant = await this.restaurant.findById(restaurantId);
if (!restaurant) {
return next(new RestaurantNotFoundException(restaurantId));
}
const user = await this.user.findById(request.user._id);
const postComment: CreateCommentDto = request.body;
if (postComment.comment.length <2) {
return next(new CommentTooShort());
}
const createdComment = await this.comment.create({
...postComment,
user: [request.user._id],
restaurant: [request.params.restaurantId],
});

const restaurantsComments = restaurant.get('comments', null, {getters: false});
const userComments = user.get('comments', null, {getters: false});
userComments.push(createdComment);
restaurantsComments.push(createdComment);
const savedComment = await createdComment.save();
await savedComment.populate('restaurant','name').execPopulate();
await savedComment.populate('user', 'lastName').execPopulate();
await this.restaurant.findByIdAndUpdate(restaurantId, {
comments: restaurant.comments
}, { new: true });
await this.user.findByIdAndUpdate(request.user._id, {
comments: user.comments
}, { new: true });
response.send(savedComment);
} catch {
next(new CommentIsNotExist());
}
};

private deleteComment = async (request: RequestWithUser, response: Response, next: NextFunction) => {
const id = request.params.id;
try {
await this.comment.findByIdAndDelete(id, { ...request.body }, (err, comment) => {
!err ? response.send(comment) : next(new CommentIsNotExist());
});
} catch {
next(new WrongCredentialsException());
}
};

private editComment = async (request: RequestWithUser, response: Response, next: NextFunction) => {
const id = request.params.id;
const dataToEdit = request.body;
try {
if (dataToEdit.comment.length < 2) {
return next(new CommentTooShort());
}
const comment = await this.comment.findByIdAndUpdate(id, { ...dataToEdit }, { new: true })
response.send({comment});
} catch {
next(new CommentIsNotExist());
}
};
}

export default CommentsController;
5 changes: 3 additions & 2 deletions server/src/controllers/favourite.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import RestaurantIsNotonTheList from '../exceptions/RestaurantIsNotOnTheList';
import permissionMiddleware from '../middleware/permission.middleware';
import authMiddleware from '../middleware/auth.middleware';
import { Operation } from '../constans/index';
import favouriteEditMiddleware from '../middleware/editFavourites.middleware';

class FavouriteController implements Controller {
public path = '/favourites';
Expand All @@ -21,8 +22,8 @@ class FavouriteController implements Controller {
}

private initializeRoutes() {
this.router.get(`${this.path}/:userId`, authMiddleware, permissionMiddleware, this.getFavourites);
this.router.put(`${this.path}/:userId`, authMiddleware, permissionMiddleware, this.addOrRemoveRestaurantToFavourites);
this.router.get(`${this.path}/:userId`, authMiddleware, this.getFavourites);
this.router.put(`${this.path}/:userId`, authMiddleware, favouriteEditMiddleware, this.addOrRemoveRestaurantToFavourites);
}

private addOrRemoveRestaurantToFavourites = async (request: Request, response: Response, next: NextFunction) => {
Expand Down
2 changes: 1 addition & 1 deletion server/src/controllers/restaurant.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class RestaurantController implements Controller {
private getRestaurantById = async (request: Request, response: Response, next: NextFunction) => {
const id = request.params.id;
try {
const restaurant = await this.restaurant.findById(id).populate('address');
const restaurant = await this.restaurant.findById(id).populate('address').populate('comments');
restaurant ? response.send(restaurant) : next(new RestaurantNotFoundException(id));
} catch {
next(new RestaurantNotFoundException(id));
Expand Down
9 changes: 9 additions & 0 deletions server/src/dto/comment.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// @ts-ignore
import { IsString } from 'class-validator';

class CreateCommentDto {
@IsString()
public comment: string;
}

export default CreateCommentDto;
7 changes: 5 additions & 2 deletions server/src/dto/restaurant.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// @ts-ignore
import { IsArray, IsBoolean, IsNumber, IsOptional, IsString, ValidateNested } from 'class-validator';
import CreateAddressDto from './address.dto';
import CreateCommentDto from './comment.dto';
import CreateUserDto from "./user.dto";

class CreateRestaurantDto {
@IsString()
Expand Down Expand Up @@ -40,8 +42,9 @@ class CreateRestaurantDto {
public socials: string[];

@IsOptional()
@ValidateNested()
@IsArray()
public comments: string[];
public comments: [CreateCommentDto];

@IsOptional()
@IsNumber()
Expand All @@ -52,4 +55,4 @@ class CreateRestaurantDto {
public dislikeCount: number;
}

export default CreateRestaurantDto;
export default CreateRestaurantDto;
11 changes: 6 additions & 5 deletions server/src/dto/user.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// @ts-ignore
import {IsArray, IsBoolean, IsNumber, IsOptional, IsString, ValidateNested} from 'class-validator';
import CreateAddressDto from './address.dto';
import CreateCommentDto from './comment.dto';

class CreateUserDto {
@IsString()
Expand All @@ -24,6 +25,10 @@ class CreateUserDto {
public address?: CreateAddressDto;

@IsOptional()
@ValidateNested()
@IsArray()
public comments: [CreateCommentDto];

@IsNumber()
public userRole: number;

Expand All @@ -42,10 +47,6 @@ class CreateUserDto {
@IsOptional()
@IsArray()
public favourites: string[];

@IsOptional()
@IsArray()
public comments: string[];
}

export default CreateUserDto;
export default CreateUserDto;
10 changes: 10 additions & 0 deletions server/src/exceptions/CommentIsNotExist.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import HttpException from './HttpException';

class CommentIsNotExist extends HttpException {
constructor() {
const idErrorMessage = `There is no such comment`;
super(400, idErrorMessage);
}
}

export default CommentIsNotExist;
10 changes: 10 additions & 0 deletions server/src/exceptions/CommentTooShort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import HttpException from './HttpException';

class CommentTooShort extends HttpException {
constructor() {
const idErrorMessage = `The comment must have more than one letter`;
super(400, idErrorMessage);
}
}

export default CommentTooShort;
10 changes: 10 additions & 0 deletions server/src/exceptions/UserDoesNotDeleteThisComment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import HttpException from './HttpException';

class UserDoesNotHavePermissionToDeleteThisComment extends HttpException {
constructor() {
const idErrorMessage = `User does not have permission to delete this comment`;
super(403, idErrorMessage);
}
}

export default UserDoesNotHavePermissionToDeleteThisComment;
10 changes: 10 additions & 0 deletions server/src/exceptions/UserDoesNotPermissiontoEditThisComment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import HttpException from './HttpException';

class UserDoesNotHavePermissionToEditThisComment extends HttpException {
constructor() {
const idErrorMessage = `User does not have permission to edit this comment`;
super(403, idErrorMessage);
}
}

export default UserDoesNotHavePermissionToEditThisComment;
10 changes: 10 additions & 0 deletions server/src/exceptions/UserDoesNotPerrmissionToEditFavourites.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import HttpException from './HttpException';

class UserDoesNotHavePermissionToEditThisFavourtie extends HttpException {
constructor() {
const idErrorMessage = `User does not have permission to edit this favourites`;
super(403, idErrorMessage);
}
}

export default UserDoesNotHavePermissionToEditThisFavourtie;
8 changes: 8 additions & 0 deletions server/src/interfaces/comments.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
interface Comments {
_id: string,
comment: string,
user: string
restaurant: string
}

export default Comments;
32 changes: 32 additions & 0 deletions server/src/middleware/commentDelete.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import RequestWithUser from '../interfaces/requestWithUser.interface';
import { NextFunction, Response } from 'express';
import UserDoesNotHavePermissionToExecutedRequestedData from '../exceptions/UserDoesNotHavePermissionToExecutedRequestedData';
import commentsModel from '../models/comments.model';
import CommentIsNotExist from '../exceptions/CommentIsNotExist';
import UserDoesNotHavePermissionToDeleteThisComment from '../exceptions/UserDoesNotDeleteThisComment';

async function commentDeleteMiddleware(request: RequestWithUser, response: Response, next: NextFunction) {
const commentId = request.params.id;
let selectedComment = null;
const userRole = request.user.userRole;
const userId = request.user._id;
const comment = commentsModel;

try {
selectedComment = await comment.findById(commentId);
const commentOwner = selectedComment.user !== null && selectedComment.user;
if ( userRole === 2) {
commentOwner.toString() === userId.toString()
? next()
: next(new UserDoesNotHavePermissionToDeleteThisComment());
} else if ( userRole === 0) {
next();
} else {
next(new UserDoesNotHavePermissionToExecutedRequestedData());
}
} catch (error) {
next(new CommentIsNotExist());
}
}

export default commentDeleteMiddleware;
30 changes: 30 additions & 0 deletions server/src/middleware/editComment.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import RequestWithUser from '../interfaces/requestWithUser.interface';
import { NextFunction, Response } from 'express';
import UserDoesNotHavePermissionToExecutedRequestedData from '../exceptions/UserDoesNotHavePermissionToExecutedRequestedData';
import commentsModel from '../models/comments.model';
import CommentIsNotExist from '../exceptions/CommentIsNotExist';
import UserDoesNotHavePermissionToEditThisComment from '../exceptions/UserDoesNotPermissiontoEditThisComment';

async function commentEditMiddleware(request: RequestWithUser, response: Response, next: NextFunction) {
const commentId = request.params.id;
let selectedComment = null;
const userRole = request.user.userRole;
const userId = request.user._id;
const comment = commentsModel;

try {
selectedComment = await comment.findById(commentId);
const commentOwner = selectedComment.user !== null && selectedComment.user;
if ( userRole === 2) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if ( userRole === 2) {
if ( userRole === userRoles.User) {

We have to make a map that will hold these numeric values

commentOwner.toString() === userId.toString()
? next()
: next (new UserDoesNotHavePermissionToEditThisComment());
} else {
next (new UserDoesNotHavePermissionToExecutedRequestedData());
}
} catch (error) {
next(new CommentIsNotExist());
}
}

export default commentEditMiddleware;
Loading