Skip to content

Commit

Permalink
Merge pull request #67 from MeetDOD/paginationapi-issue-40
Browse files Browse the repository at this point in the history
feat: Added Pagination for posts section with backend api successfully Issue 40
  • Loading branch information
VaibhavArora314 authored Jun 1, 2024
2 parents 622ab41 + 146614d commit f74056e
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 25 deletions.
78 changes: 57 additions & 21 deletions backend/src/routes/post/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,28 +83,28 @@ export const createPostController = async (
}
};

export const getPostsController = async (req: Request, res: Response) => {
const posts = await prisma.post.findMany({
select: {
id: true,
title: true,
codeSnippet: true,
description: true,
tags: true,
author: {
select: {
id: true,
username: true,
email: true,
},
},
},
});
// export const getPostsController = async (req: Request, res: Response) => {
// const posts = await prisma.post.findMany({
// select: {
// id: true,
// title: true,
// codeSnippet: true,
// description: true,
// tags: true,
// author: {
// select: {
// id: true,
// username: true,
// email: true,
// },
// },
// },
// });

res.status(200).json({
posts,
});
};
// res.status(200).json({
// posts,
// });
// };

export const getPostController = async (req: Request, res: Response) => {
try {
Expand Down Expand Up @@ -145,3 +145,39 @@ export const getPostController = async (req: Request, res: Response) => {
});
}
};

export const getPostsWithPagination = async (req: Request, res: Response) => {
try {
const page = parseInt(req.query.page as string);
const pageSize = parseInt(req.query.pageSize as string);

const totalPosts = await prisma.post.count();
const totalPages = Math.ceil(totalPosts / pageSize);

const posts = await prisma.post.findMany({
skip: (page - 1) * pageSize,
take: pageSize,
select: {
id: true,
title: true,
codeSnippet: true,
description: true,
tags: true,
author: {
select: {
id: true,
username: true,
email: true,
},
},
},
});

res.status(200).json({
posts,
totalPages,
});
} catch (error) {
res.status(500).json({ error: 'Failed to fetch posts' });
}
};
4 changes: 2 additions & 2 deletions backend/src/routes/post/route.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Router } from "express";
import authMiddleware from "../../middleware/auth"
import { createPostController, getPostController, getPostsController } from "./controller";
import { createPostController, getPostController, getPostsWithPagination } from "./controller";

const postRouter = Router();

postRouter.get('/', getPostsController)
postRouter.get('/', getPostsWithPagination);

postRouter.post('/', authMiddleware, createPostController)

Expand Down
46 changes: 44 additions & 2 deletions frontend/src/pages/Posts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@ const Posts = () => {
const [filterTags, setFilterTags] = useState<string[]>([]);
const filterRef = useRef<HTMLDivElement>(null);
const [searchQuery, setSearchQuery] = useState('');
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);

useEffect(() => {
const fetchPosts = async () => {
try {
const response = await axios.get('/api/v1/posts');
setLoading(true);
const response = await axios.get(`/api/v1/posts?page=${page}&pageSize=12`);
setPosts(response.data.posts);
setTotalPages(response.data.totalPages);
setLoading(false);
} catch (error) {
setError('Failed to fetch posts');
Expand All @@ -27,7 +31,7 @@ const Posts = () => {
};

fetchPosts();
}, []);
}, [page]);

useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
Expand Down Expand Up @@ -71,6 +75,22 @@ const Posts = () => {
post.author.username.toLowerCase().includes(searchQuery.toLowerCase()))
);

const handlePreviousPage = () => {
if (page > 1) {
setPage(page - 1);
}
};

const handleNextPage = () => {
if (page < totalPages) {
setPage(page + 1);
}
};

const handlePageClick = (pageNumber: number) => {
setPage(pageNumber);
};

if (loading) {
return <Loader />;
}
Expand Down Expand Up @@ -143,6 +163,28 @@ const Posts = () => {
<PostCard key={index} post={post} />
))}
</div>
<div className="flex justify-center items-center mt-4 w-full space-x-2">
<button
onClick={handlePreviousPage}
disabled={page === 1}
className={`text-white px-4 py-2 rounded ${page === 1 ? 'bg-gray-600 cursor-not-allowed' : 'bg-blue-600 hover:bg-blue-700'}`} >
Previous
</button>
{Array.from({ length: totalPages }, (_, i) => (
<button
key={i}
onClick={() => handlePageClick(i + 1)}
className={`text-white px-4 py-2 rounded ${page === i + 1 ? 'bg-blue-500 text-white' : 'bg-blue-600 hover:bg-blue-700'}`} >
{i + 1}
</button>
))}
<button
onClick={handleNextPage}
disabled={page === totalPages}
className={`text-white px-6 py-2 rounded ${page === totalPages ? 'bg-gray-600 cursor-not-allowed' : 'bg-blue-600 hover:bg-blue-700'}`} >
Next
</button>
</div>
</div>
);
};
Expand Down

0 comments on commit f74056e

Please sign in to comment.