Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
177 commits
Select commit Hold shift + click to select a range
6a2f39d
set up sequelize init
charlesleezhaoyi Mar 15, 2024
2526d6a
Created first migration and seeder file for user entity (firstName, l…
charlesleezhaoyi Mar 15, 2024
2e7846b
Created baseController, usersController and usersRouter - POST req to…
charlesleezhaoyi Mar 15, 2024
3dceb4d
Made changes to the original migration file for users
charlesleezhaoyi Mar 16, 2024
d68bd64
Modified insertUser controller logic to validate if user already exis…
charlesleezhaoyi Mar 16, 2024
d768bb6
added category model, and junction table for user_categories
charlesleezhaoyi Mar 18, 2024
7f36e14
made changes based on PR comments from Ian
charlesleezhaoyi Mar 19, 2024
b011099
added underscored: true for category.js
charlesleezhaoyi Mar 19, 2024
e5ff760
Merge pull request #1 from charlesleezhaoyi/test-setup
ianlauyin Mar 19, 2024
6ff8a1a
installed packages
Qiannnly Mar 19, 2024
8832eb6
Added Post Migration and Model
ianlauyin Mar 19, 2024
5215737
Added Migration and Model for comment
ianlauyin Mar 19, 2024
c83785e
Updated Migration and Model for like and category_post joint table
ianlauyin Mar 19, 2024
1680ba8
added junction table with books table
Qiannnly Mar 20, 2024
0a17b40
added associations with photo and donation tables
Qiannnly Mar 20, 2024
3963dec
added association with book table
Qiannnly Mar 20, 2024
8e5e3fa
added associations with request and donation tables
Qiannnly Mar 20, 2024
c24f654
added associations with user tables
Qiannnly Mar 20, 2024
e9a7f7a
added assocation with request table
Qiannnly Mar 20, 2024
6367fb8
added association with donation table
Qiannnly Mar 20, 2024
ca9fda7
added association with book table
Qiannnly Mar 20, 2024
aa343f9
added junction table with category
Qiannnly Mar 20, 2024
6721634
specified foreign key references
Qiannnly Mar 20, 2024
1e70e44
specified foreign key references
Qiannnly Mar 20, 2024
7d962b4
specified foreign key references
Qiannnly Mar 20, 2024
46d48ea
created migration file for category_books junction table
Qiannnly Mar 20, 2024
992de9a
installed packages
Qiannnly Mar 20, 2024
6684fdc
populated 3 books
Qiannnly Mar 20, 2024
284ae75
added insert book logic
Qiannnly Mar 20, 2024
4fb98d0
added retrieve all books and insert book routers
Qiannnly Mar 20, 2024
ec244e5
added books router and controller
Qiannnly Mar 20, 2024
ca995aa
updated file
Qiannnly Mar 20, 2024
994a71c
Merge pull request #2 from charlesleezhaoyi/test-forum-model-and-migr…
Qiannnly Mar 20, 2024
eaf3955
updated files
Qiannnly Mar 20, 2024
769ef63
populated data
Qiannnly Mar 20, 2024
9112d5a
updated file
Qiannnly Mar 20, 2024
8dfdde4
updated file
Qiannnly Mar 20, 2024
7f79540
updated files
Qiannnly Mar 20, 2024
41db171
Added Seed for category
ianlauyin Mar 20, 2024
36b83ef
Setted Up for category and post controller and router
ianlauyin Mar 20, 2024
78430c7
Fixed Association with alias in user and post
ianlauyin Mar 20, 2024
b61432c
Added and Tested Create Post
ianlauyin Mar 20, 2024
f9a42ca
Added function for creatingComment
ianlauyin Mar 20, 2024
aafdfc9
updated model reference
Qiannnly Mar 21, 2024
84ba10a
updated model reference
Qiannnly Mar 21, 2024
806ed05
updated model reference
Qiannnly Mar 21, 2024
4a99b67
populated category rows
Qiannnly Mar 21, 2024
6ff88a3
added aliases and foreign keys to associations
Qiannnly Mar 21, 2024
58e8563
Added validation check for category in createPost and added transcation
ianlauyin Mar 21, 2024
7d088c2
Refactor create post to reduce interaction with DB
ianlauyin Mar 21, 2024
acf7aba
added allowNull to true
Qiannnly Mar 21, 2024
3ebbcd4
updated associations
Qiannnly Mar 21, 2024
9fc14b0
updated file
Qiannnly Mar 21, 2024
a09bb80
Merge pull request #3 from charlesleezhaoyi/test-migration
Qiannnly Mar 21, 2024
5566195
Added Router for getting comments for a post
ianlauyin Mar 21, 2024
33afa03
Added getComments related to Post
ianlauyin Mar 21, 2024
566075a
Added Toggle like for post
ianlauyin Mar 21, 2024
82be93f
Changed foreign key name in like and comment
ianlauyin Mar 21, 2024
87871b5
Changed Controller due to the change of column name
ianlauyin Mar 21, 2024
42844e4
Refactor toggle like due to change of column name
ianlauyin Mar 21, 2024
fcf0207
added categories included in getOne of posts
ianlauyin Mar 21, 2024
3076ed2
Added getPostsFromCategory with newestPost sorting with limit and pag…
ianlauyin Mar 22, 2024
2fcf918
Fixed toggleLike bug
ianlauyin Mar 22, 2024
2cdefb9
Added likeCount for getPostsFromCategory and sortBy popular avaiable
ianlauyin Mar 22, 2024
ce66e1c
Completed getPostsFromCategory
ianlauyin Mar 22, 2024
7cabd9b
Merge pull request #4 from charlesleezhaoyi/test-forum-controller-and…
Qiannnly Mar 23, 2024
3664fea
Settup Route for getAllCategoriesWithSortBy
ianlauyin Mar 23, 2024
9dba3cc
Merge branch 'test' into test-forum-category
ianlauyin Mar 23, 2024
c6e0332
Added Popular Sort in getAllCategoriesWithSortBy
ianlauyin Mar 23, 2024
45c33fa
Added Seed for post,comment,like and category_posts
ianlauyin Mar 23, 2024
07a448a
Added sort for getAllCategoryWithSort
ianlauyin Mar 23, 2024
bc296db
Added sort popular for getSortedCategories
ianlauyin Mar 23, 2024
4c92c08
created method to add category to user via user_categories, and updat…
charlesleezhaoyi Mar 24, 2024
4d1881f
Merge pull request #5 from charlesleezhaoyi/test-forum-category
ianlauyin Mar 25, 2024
95d31b2
Added getUserByEmail
ianlauyin Mar 26, 2024
959715d
Changed getting userEmail instead of userId when create Post and Comment
ianlauyin Mar 26, 2024
bb3f632
Fixed getPostsFromCategory bug
ianlauyin Mar 27, 2024
ec3630f
Updated seed for post and comment
ianlauyin Mar 28, 2024
36b34ba
Added comments in getOne from post
ianlauyin Mar 28, 2024
f56070f
Added route for getting isUserLikedPost
ianlauyin Mar 28, 2024
cea9d1f
Added like check for toggle like
ianlauyin Mar 28, 2024
8005b6f
Fixed toggleLike bug
ianlauyin Mar 28, 2024
51f2d59
Added commenter for getOne post
ianlauyin Mar 28, 2024
16d7e8a
Updated Post and comments date seed
ianlauyin Mar 28, 2024
4dad95a
Updated Date for post and comment again
ianlauyin Mar 28, 2024
ded4be6
Add return from createComment for user and comment data
ianlauyin Mar 29, 2024
d5d537a
added books and categories routes
Qiannnly Mar 29, 2024
1f98d80
Merge pull request #7 from charlesleezhaoyi/test-find-user-by-email
Qiannnly Mar 31, 2024
ca17378
updated controllers
Qiannnly Mar 31, 2024
79c7dc3
merged files
Qiannnly Mar 31, 2024
be69160
fetched test branch changes and merged to test-user-category
charlesleezhaoyi Mar 31, 2024
c833030
Fixed seeder bug
ianlauyin Mar 31, 2024
f68117f
Merge pull request #8 from charlesleezhaoyi/test-logic
ianlauyin Mar 31, 2024
5a37054
merged test into current
ianlauyin Mar 31, 2024
2037450
Fixed typo in index.js requestsController
ianlauyin Mar 31, 2024
f155d04
merge CategoriesController into categoriesController
ianlauyin Mar 31, 2024
536b18a
Fixed Route order for category
ianlauyin Mar 31, 2024
bb2b044
added logic for request
Qiannnly Apr 1, 2024
122e32e
added logic to create donation upon submitting a new book
Qiannnly Apr 1, 2024
0fb0306
added logic to create and update users
Qiannnly Apr 1, 2024
15974c3
updated files
Qiannnly Apr 1, 2024
56d6a0f
Merge pull request #9 from charlesleezhaoyi/test-seeder-bug-fix
Qiannnly Apr 1, 2024
28fe699
updated files
Qiannnly Apr 1, 2024
9554612
updated files
Qiannnly Apr 1, 2024
e1b29c4
added user seed
Qiannnly Apr 1, 2024
91e0a58
Merge pull request #10 from charlesleezhaoyi/test-logic
ianlauyin Apr 1, 2024
1a1ef78
modified demo user seeder
charlesleezhaoyi Apr 1, 2024
8474802
Merge branch 'test' into test-user-category
charlesleezhaoyi Apr 1, 2024
12f5801
Fixed CategoryController
ianlauyin Apr 1, 2024
1ca7bcc
Request Controller no longer extends base controller
ianlauyin Apr 1, 2024
7fe4318
created base code for search, as well as updated seed files for seed-…
charlesleezhaoyi Apr 1, 2024
fe8cc40
Updated with association between user,book,request,donation
ianlauyin Apr 1, 2024
6257014
Added get Requests based on user and book
ianlauyin Apr 1, 2024
5f85887
Added get Donations base on user
ianlauyin Apr 1, 2024
ddc850f
Added get Request base on book
ianlauyin Apr 1, 2024
b8736da
Merge pull request #11 from charlesleezhaoyi/test-request
Qiannnly Apr 2, 2024
93c4fe2
Fixed bug in donation Controller and insertBook
ianlauyin Apr 2, 2024
159bedb
Change route due to functionality in getDonorEmail
ianlauyin Apr 2, 2024
70c2ff8
Merge pull request #13 from charlesleezhaoyi/test-donation-bug
Qiannnly Apr 2, 2024
9e47f1a
Fixed donor email bug
ianlauyin Apr 2, 2024
458d45f
Merge pull request #14 from charlesleezhaoyi/test-donation-bug
Qiannnly Apr 2, 2024
b3e582e
Updated with accept request
ianlauyin Apr 2, 2024
4b46533
Fixed bug
ianlauyin Apr 2, 2024
6b1502e
Merge pull request #15 from charlesleezhaoyi/test-donation-bug
Qiannnly Apr 2, 2024
fbb1f60
Merge branch 'test' into test-user-category-2
charlesleezhaoyi Apr 2, 2024
93ce61c
changed userEmail to email
charlesleezhaoyi Apr 2, 2024
ef077ad
Merge pull request #16 from charlesleezhaoyi/test-user-category-2
ianlauyin Apr 2, 2024
aa709a4
Added User for getOneBook
ianlauyin Apr 2, 2024
7772cd1
Added migration file for photo
ianlauyin Apr 2, 2024
c4f9cfc
Refactor insertBook
ianlauyin Apr 2, 2024
a522b0e
Fixed bug with getAllBooks
ianlauyin Apr 2, 2024
95e002f
Fixed Upload photo bug in insertBook
ianlauyin Apr 3, 2024
fb5ea7b
Updated Upload file to save memory
ianlauyin Apr 3, 2024
546a4a2
Change getCategory to getBookByCateogry
ianlauyin Apr 3, 2024
c76d041
Merge pull request #17 from charlesleezhaoyi/test-single-book
charlesleezhaoyi Apr 6, 2024
59f18d4
Fix donation and request bugs
ianlauyin Apr 6, 2024
bf87b15
Fixed Bugs
ianlauyin Apr 6, 2024
3f47332
Fixed merging bugs
ianlauyin Apr 6, 2024
88e7f4b
Merge pull request #18 from charlesleezhaoyi/test-fix-donations-bug
charlesleezhaoyi Apr 6, 2024
bf7d946
Add route for getUserByEmail
ianlauyin Apr 6, 2024
13db1c1
Merge pull request #19 from charlesleezhaoyi/test-fix-setting
charlesleezhaoyi Apr 6, 2024
8c3ac93
Added Route for changing Status
ianlauyin Apr 7, 2024
810f2bd
Added requestList for getDonationsOnUser
ianlauyin Apr 7, 2024
784689e
Merge pull request #20 from charlesleezhaoyi/test-request
charlesleezhaoyi Apr 7, 2024
e8c1b68
made changes to support onboarding form sms consent and send twilio SMS
charlesleezhaoyi Apr 7, 2024
78d19d4
Merge branch 'test' into test-twilio-sms
charlesleezhaoyi Apr 7, 2024
83e254b
completed feature for twilio-sms
charlesleezhaoyi Apr 7, 2024
cf15e33
fixed missing import for sequelize Op
charlesleezhaoyi Apr 7, 2024
c2d063e
created search logic and email
Qiannnly Apr 9, 2024
8369a1c
amended based on Ian's review
charlesleezhaoyi Apr 9, 2024
6e87071
Merge pull request #21 from charlesleezhaoyi/test-twilio-sms
ianlauyin Apr 9, 2024
eefd08e
Merge branch 'test' into test-email-search
ianlauyin Apr 9, 2024
333ebb5
Merge pull request #22 from charlesleezhaoyi/test-email-search
ianlauyin Apr 9, 2024
eb98a35
Updated with email Consent and email notification in accpetRequest
ianlauyin Apr 9, 2024
ad81b18
Merge pull request #23 from charlesleezhaoyi/test-email-refactor
charlesleezhaoyi Apr 12, 2024
da96add
made backend changes to support protected routes
charlesleezhaoyi Apr 12, 2024
933c8a3
Merge branch 'test' into test-checkJwt
charlesleezhaoyi Apr 12, 2024
9a81b8c
Added checkJwt to relevant routers
charlesleezhaoyi Apr 12, 2024
60aadf6
added changes to usersRouters and requestsRouter
charlesleezhaoyi Apr 12, 2024
bc0e3e2
fixed comments raised during PR review
charlesleezhaoyi Apr 13, 2024
25f93ab
Merge pull request #24 from charlesleezhaoyi/test-checkJwt
ianlauyin Apr 13, 2024
276fef3
Fixed bug in toggleLike
ianlauyin Apr 14, 2024
3dc9233
Combined Repeated getAll category route
ianlauyin Apr 14, 2024
53e4139
Protected User Route
ianlauyin Apr 14, 2024
2592ce6
Move checkJwt into app.use middleware
ianlauyin Apr 15, 2024
3d5ca9f
Changed changed RequestStatus from post to put
ianlauyin Apr 15, 2024
cc8b566
Updated books controller
ianlauyin Apr 15, 2024
80fb22a
Add type check on id in bookscontroller
ianlauyin Apr 15, 2024
b714682
Updated acceptRequest
ianlauyin Apr 15, 2024
b3407bf
Updated number type check in request controller
ianlauyin Apr 15, 2024
b39ea53
Updated user controller
ianlauyin Apr 15, 2024
03a878e
Added validation checker
ianlauyin Apr 15, 2024
291b01e
Fixed Transcaction
ianlauyin Apr 15, 2024
5035794
Merge pull request #25 from charlesleezhaoyi/test-final-fix
ianlauyin Apr 15, 2024
b18ba78
Fix transaction
ianlauyin Apr 15, 2024
2558406
Merge pull request #26 from charlesleezhaoyi/test-final-fix
ianlauyin Apr 15, 2024
9273dc9
Merge pull request #28 from charlesleezhaoyi/test
ianlauyin Apr 16, 2024
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules/
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

no README

node_modules/
.env
8 changes: 8 additions & 0 deletions .sequelizerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const path = require("path");

module.exports = {
config: path.resolve("config", "database.js"),
"models-path": path.resolve("db", "models"),
"seeders-path": path.resolve("db", "seeders"),
"migrations-path": path.resolve("db", "migrations"),
};
11 changes: 11 additions & 0 deletions config/database.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
require("dotenv").config();

module.exports = {
development: {
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DIALECT,
},
};
50 changes: 50 additions & 0 deletions controllers/CommentsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const ValidationChecker = require("./ValidationChecker");

class CommentsController extends ValidationChecker {
constructor(db) {
super();
this.commentModel = db.comment;
this.postModel = db.post;
this.userModel = db.user;
}

async getComments(req, res) {
const { postId } = req.params;
try {
this.checkNumber(postId, "postId");
const comments = await this.commentModel.findAll({
where: { commentedPostId: postId },
include: "commenter",
order: [["createdAt", "ASC"]],
});
return res.json(comments);
} catch (error) {
return res.status(400).json({ error: true, msg: error });
}
}

async createComment(req, res) {
const { postId } = req.params;
try {
this.checkNumber(postId, "postId");
const { userEmail, content } = req.body;
this.checkStringFromBody(userEmail, "userEmail");
this.checkStringFromBody(content, "content");
Comment on lines +29 to +32
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

you could check express-validator for something similar

const postData = await this.postModel.findByPk(postId);
if (!postData) {
throw new Error("No Such Post Found.");
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

When you do this, you basically respond with 400 (bad request). Whereas here you have a scenario that there was no post found. So this kinda returns the wrong status code. We should handle this in a different manner, with the correct status code applied

}
const user = await this.userModel.findOne({
where: { email: userEmail },
});
const comment = await postData.createComment({
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

What if no user was found, how can you created a comment? This could potentially create corrupted data

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Also, since the user email comes from the req.body, I could probably create a comment for other users

commenterId: user.id,
content,
});
return res.json({ user, comment });
} catch (error) {
return res.status(400).json({ error: true, msg: error });
}
}
}
module.exports = CommentsController;
198 changes: 198 additions & 0 deletions controllers/PostsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
const ValidationChecker = require("./ValidationChecker");
class PostsController extends ValidationChecker {
constructor(db) {
super();
this.postModel = db.post;
this.userModel = db.user;
this.categoryModel = db.category;
this.commentModel = db.comment;
this.likeModel = db.like;
this.sequelize = db.sequelize;
}

async getOne(req, res) {
const { postId } = req.params;
try {
this.checkNumber(postId, "postId");
const data = await this.postModel.findByPk(postId, {
include: [
"author",
"likes",
"categories",
{
model: this.commentModel,
include: { model: this.userModel, as: "commenter" },
},
],
});
return res.json(data);
} catch (error) {
return res.status(400).json({ error: true, msg: error });
}
}

async getPostsFromCategory(req, res) {
const { category } = req.params;
let { sortBy, limit, page } = req.query;
const sortByList = ["newestPost", "newestComment", "popular"];
try {
this.checkStringFromParams(category, "category");
if (limit) {
this.checkNumber(limit, "limit");
}
if (page) {
this.checkNumber(page, "page");
}
if (!!page && !limit) {
throw new Error("Must have limit for page");
}
if (!!sortBy && !sortByList.includes(sortBy)) {
throw new Error(
`ValueError: Wrong value of sortBy ("newestPost"/"newestComment"/"popular")`
);
}
Comment on lines +38 to +53
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I feel we should handle this with some kind of middleware and abstract it away.

const postsOption = this.getPostsOption(sortBy, limit, page);
const categoryInstance = await this.categoryModel.findOne({
where: { name: category },
});
if (!categoryInstance) {
throw new Error(`Category: ${category} cannot be found `);
}
const posts = await categoryInstance.getPosts({
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Why not just eagerLoad the posts of the category? That way you don't need to query the DB twice

joinTableAttributes: [],
...postsOption,
});
if (!!limit) {
const offset = page ? (page - 1) * limit : 0;
return res.json(posts.slice(offset, limit));
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

you should use offset and limit on the DB query itself, not as a slice operation :) The DB will offset and limit for you already

}
return res.json(posts);
} catch (error) {
return res.status(400).json({ error: true, msg: error });
}
}

getPostsOption(sortBy) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I would pluralize this, as you get multiple options returned

const postsOption = {
include: ["author", { model: this.likeModel, attributes: [] }],
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

why are the attributes empty? Do we need those?

group: ["post.id", "author.id"],
attributes: {
include: [
[
this.sequelize.fn("COUNT", this.sequelize.col("likes.id")),
"likeCount",
],
],
},
};
switch (sortBy) {
case "newestPost":
postsOption.order = [["createdAt", "DESC"]];
break;
case "newestComment":
postsOption.include.push({
model: this.commentModel,
attributes: [],
});
postsOption.group.push("comments.created_at");
postsOption.order = [["comments", "createdAt", "DESC"]];
break;
case "popular":
postsOption.order = [["likeCount", "DESC"]];
break;
}
return postsOption;
}

async createPost(req, res) {
const { categories, authorEmail, ...data } = req.body;
const t = await this.sequelize.transaction();
try {
this.checkStringFromBody(authorEmail, "authorEmail");
this.checkStringFromBody(data.title, "title");
this.checkStringFromBody(data.content, "content");
this.checkArray(categories, "categories");
const author = await this.userModel.findOne({
where: { email: authorEmail },
});
data.authorId = author.id;
const newPost = await this.postModel.create(data, { transaction: t });
await this.addingCategoriesToPost(categories, newPost, t);
await t.commit();
return res.send(newPost);
} catch (error) {
await t.rollback();
return res.status(400).json({ error: true, msg: error });
}
}

async addingCategoriesToPost(categories, post, t) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggested change
async addingCategoriesToPost(categories, post, t) {
async addCategoriesToPost(categories, post, t) {

const categoryInstances = [];
for (const category of categories) {
const categoryInstance = await this.categoryModel.findOne({
where: { name: category },
});
if (!categoryInstance) {
throw new Error(`Category name "${category}" cannot be found.`);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

As stated above, we shouldn't always throw errors and return 400 across the board. By right the catch block should be used to return 500 for UNEXPECTED server errors. All other errors, that we know of and could be in control of, should be handled with an appropriate status code and error message - that would be best practice

}
categoryInstances.push(categoryInstance);
}
await post.setCategories(categoryInstances, { transaction: t });
}

async checkIsUserLikedPost(postId, userEmail) {
const post = await this.postModel.findByPk(postId);
if (!post) {
throw new Error("No Such Post Found");
}
const user = await this.userModel.findOne({ where: { email: userEmail } });
if (!post) {
throw new Error("No Such User Found");
}
const isUserLikedPost = await post.hasLiker(user);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

isUserLikedPost and hasLiker, both names are bit confusing to me. This doesn't read nicely, and should be renamed ideally.

isPostLikedByUser would make more sense for the variable and the function name.

return [isUserLikedPost, post, user];
}

async getIsUserLikedPost(req, res) {
const { postId, userEmail } = req.params;
try {
this.checkNumber(postId, "postId");
this.checkStringFromParams(userEmail, "userEmail");
const [isUserLikedPost] = await this.checkIsUserLikedPost(
postId,
userEmail
);
return res.json(isUserLikedPost);
} catch (error) {
return res.status(400).json({ error: true, msg: error });
}
}

async toggleLike(req, res) {
const { postId, userEmail, like } = req.body;
try {
this.checkNumber(postId, "postId");
this.checkStringFromBody(userEmail, "userEmail");
const [isUserLikedPost, post, user] = await this.checkIsUserLikedPost(
postId,
userEmail
);
if (like !== isUserLikedPost) {
throw new Error(
`User already ${
isUserLikedPost ? "liked" : "unliked"
} this post before`
);
}
if (isUserLikedPost) {
await post.removeLiker(user);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

removeLike and addLike should be enough. Seeing that the parameter is a user, it is clear that this is applied on a user-basis

} else {
await post.addLiker(user);
}
return res.json(!isUserLikedPost);
} catch (error) {
return res.status(400).json({ error: true, msg: error });
}
}
}
module.exports = PostsController;
27 changes: 27 additions & 0 deletions controllers/ValidationChecker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class ValidationChecker {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is not a controller, so should be place in a different folder :)

checkNumber(number, idName) {
if (isNaN(Number(number))) {
throw new Error(`Wrong Type of ${idName}`);
}
}
checkStringFromParams(string, strName) {
if (!string || !string.length) {
throw new Error(`${strName} required`);
}
}
checkStringFromBody(string, strName) {
if (typeof string !== "string") {
throw new Error(`${strName} must be string`);
}
if (!string.length) {
throw new Error(`${strName} required`);
}
}
checkArray(array, arrName) {
if (!array.length) {
throw new Error(`${arrName} require at least one data.`);
}
}
}

module.exports = ValidationChecker;
Loading