Skip to content

Commit

Permalink
🛠 Update returned data from bookmarks
Browse files Browse the repository at this point in the history
  • Loading branch information
jgudo committed Mar 21, 2021
1 parent 26b598e commit 94a1717
Show file tree
Hide file tree
Showing 6 changed files with 19 additions and 64 deletions.
2 changes: 1 addition & 1 deletion frontend/.eslintcache

Large diffs are not rendered by default.

29 changes: 9 additions & 20 deletions frontend/src/pages/profile/Tabs/Bookmarks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,8 @@ interface IProps {
isOwnProfile: boolean;
}

interface IBookmarkState {
items: IBookmark[];
total: number;
}

const Bookmarks: React.FC<IProps> = ({ username, isOwnProfile }) => {
const [bookmarks, setBookmarks] = useState<IBookmarkState>({
items: [],
total: 0
});
const [bookmarks, setBookmarks] = useState<IBookmark[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<IError | null>(null);
const [offset, setOffset] = useState(0);
Expand All @@ -44,13 +36,10 @@ const Bookmarks: React.FC<IProps> = ({ username, isOwnProfile }) => {
try {
setIsLoading(true);

const { bookmarks: result, total } = await getBookmarks({ offset });
const data = await getBookmarks({ offset });

if (didMount) {
setBookmarks({
items: [...bookmarks.items, ...result],
total
});
setBookmarks(data);
setOffset(offset + 1);

setIsLoading(false);
Expand All @@ -66,31 +55,31 @@ const Bookmarks: React.FC<IProps> = ({ username, isOwnProfile }) => {

const infiniteRef = useInfiniteScroll({
loading: isLoading,
hasNextPage: !error && bookmarks.items.length >= 10,
hasNextPage: !error && bookmarks.length >= 10,
onLoadMore: fetchBookmarks,
scrollContainer: 'window',
threshold: 200
});

return (!isOwnProfile && username) ? <Redirect to={`/user/${username}`} /> : (
<div className="flex flex-col items-start justify-start w-full min-h-10rem">
{(isLoading && bookmarks.items.length === 0) && (
{(isLoading && bookmarks.length === 0) && (
<div className="flex w-full items-center justify-center min-h-10rem">
<Loader />
</div>
)}
{(bookmarks.items.length === 0 && error && !isLoading) && (
{(bookmarks.length === 0 && error && !isLoading) && (
<div className="w-full p-4 flex min-h-10rem items-center justify-center">
<span className="text-gray-400 text-lg italic">
{error?.error?.message || "Something went wrong :("}
</span>
</div>
)}
{(bookmarks.items.length !== 0 && !error) && (
{(bookmarks.length !== 0 && !error) && (
<div className="w-full space-y-4" ref={infiniteRef as React.RefObject<HTMLDivElement>}>
<h4 className="text-gray-700 dark:text-white mb-4 ml-4 mt-4 laptop:mt-0">Bookmarks</h4>
<TransitionGroup component={null}>
{bookmarks.items.map(item => (
{bookmarks.map(item => (
<CSSTransition
timeout={500}
classNames="fade"
Expand Down Expand Up @@ -135,7 +124,7 @@ const Bookmarks: React.FC<IProps> = ({ username, isOwnProfile }) => {
</CSSTransition>
))}
</TransitionGroup>
{(bookmarks.items.length !== 0 && !error && isLoading) && (
{(bookmarks.length !== 0 && !error && isLoading) && (
<div className="flex justify-center py-6">
<Loader />
</div>
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ export const markAllAsUnreadNotifications = () => {

// ---------- BOOKMARK METHODS ----------------

export const getBookmarks = (params: IFetchParams) => httpRequest<{ bookmarks: IBookmark[]; total: number; }>({
export const getBookmarks = (params: IFetchParams) => httpRequest<IBookmark[]>({
method: 'GET',
url: `/bookmarks`,
params
Expand Down
13 changes: 4 additions & 9 deletions server/src/routes/api/v1/bookmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BOOKMARKS_LIMIT } from '@/constants/constants';
import { makeResponseJson } from '@/helpers/utils';
import { ErrorHandler } from '@/middlewares/error.middleware';
import { isAuthenticated, validateObjectID } from '@/middlewares/middlewares';
import { Bookmark, Post, User } from '@/schemas';
import { Bookmark, Post } from '@/schemas';
import { NextFunction, Request, Response, Router } from 'express';
import { Types } from 'mongoose';

Expand Down Expand Up @@ -32,7 +32,6 @@ router.post(

if (isPostBookmarked) {
await Bookmark.findOneAndDelete({ _author_id: userID, _post_id: Types.ObjectId(post_id) });
await User.findByIdAndUpdate(userID, { $pull: { bookmarks: Types.ObjectId(post_id) } });

res.status(200).send(makeResponseJson({ state: false }));
} else {
Expand All @@ -42,7 +41,7 @@ router.post(
createdAt: Date.now()
});
await bookmark.save();
await User.findByIdAndUpdate(userID, { $push: { bookmarks: post_id } });

res.status(200).send(makeResponseJson({ state: true }));
}
} catch (e) {
Expand All @@ -62,8 +61,6 @@ router.get(
const limit = BOOKMARKS_LIMIT;
const skip = offset * limit;

// GET TOTAL
const countBookmarks = await Bookmark.find({ _author_id: userID });
const bookmarks = await Bookmark
.find({ _author_id: userID })
.populate({
Expand All @@ -82,15 +79,13 @@ router.get(
}

const result = bookmarks.map((item) => {
const isBookmarked = req.user.isBookmarked(item._post_id);

return {
...item.toObject(),
isBookmarked,
isBookmarked: true,
}
});

res.status(200).send(makeResponseJson({ bookmarks: result, total: countBookmarks.length }));
res.status(200).send(makeResponseJson(result));
} catch (e) {
console.log('CANT GET BOOKMARKS ', e);
next(e);
Expand Down
27 changes: 4 additions & 23 deletions server/src/routes/api/v1/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,12 @@ router.post(
});

await comment.save();
await Post
.findByIdAndUpdate(post_id, {
$push: {
comments: comment._id
}
});
await comment
.populate({
path: 'author',
select: 'username profilePicture fullname'
}).execPopulate();
})
.execPopulate();

// SEND NOTIFICATION
if (post._author_id.toString() !== userID.toString()) {
Expand Down Expand Up @@ -249,15 +244,6 @@ router.delete(
{ parents: { $in: [comment_id] } }
]
});
await Post.updateMany({
comments: {
$in: [comment_id]
}
}, {
$pull: {
comments: Types.ObjectId(comment_id)
}
});
res.sendStatus(200);
} else {
res.sendStatus(401);
Expand Down Expand Up @@ -349,17 +335,12 @@ router.post(
});

await reply.save();
await Post
.findByIdAndUpdate(post_id, {
$push: {
comments: reply._id
}
});
await reply
.populate({
path: 'author',
select: 'username profilePicture fullname'
}).execPopulate();
})
.execPopulate();

// SEND NOTIFICATION
if (req.user._id.toString() !== comment._author_id.toString()) {
Expand Down
10 changes: 0 additions & 10 deletions server/src/routes/api/v1/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,16 +280,6 @@ router.delete(
await Comment.deleteMany({ _post_id: Types.ObjectId(post_id) });
await NewsFeed.deleteMany({ post: Types.ObjectId(post_id) });
await Bookmark.deleteMany({ _post_id: Types.ObjectId(post_id) });
await User.updateMany({
bookmarks: {
$in: [post_id]
}
}, {
$pull: {
bookmarks: Types.ObjectId(post_id)
}
});


res.sendStatus(200);
} else {
Expand Down

1 comment on commit 94a1717

@vercel
Copy link

@vercel vercel bot commented on 94a1717 Mar 21, 2021

Choose a reason for hiding this comment

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

Please sign in to comment.