Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Added Pagination for posts section with backend api successfully Issue 40 #67

Merged
Merged
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
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
Loading