임태민

Create post paging function

post 목록의 paging 기능을 추가하였습니다.
......@@ -6,13 +6,28 @@ var util = require('../util');
// Post home
router.get('/', function(req, res){
Post.find({})
router.get('/', async function(req, res){
// Paging 기능 추가
var page = Math.max(1, parseInt(req.query.page));
var limit = Math.max(1, parseInt(req.query.limit));
page = !isNaN(page)?page:1;
limit = !isNaN(limit)?limit:10;
var skip = (page-1)*limit;
var count = await Post.countDocuments({});
var maxPage = Math.ceil(count/limit);
var posts = await Post.find({})
.populate('author')
.sort('-createdAt')
.exec(function(err, posts){
if(err){return res.json(err)};
res.render('posts/index', {posts:posts});
.skip(skip)
.limit(limit)
.exec();
res.render('posts/index', {
posts:posts,
currentPage:page,
maxPage:maxPage,
limit:limit
});
});
......
......@@ -47,15 +47,31 @@
</tr>
<% }) %>
</tbody>
</table>
<nav class="nav justify-content-center bg-light">
<%
var offset = 2;
var previousBtnEnabled = currentPage>1;
var nextBtnEnabled = currentPage<maxPage;
%>
<ul class="pagination pagination-sm justify-content-center align-items-center h-100 mb-0">
<li class="page-item <%= previousBtnEnabled?'':'disabled' %>">
<a class="page-link" href="/posts?page=<%= currentPage-1 %>&limit=<%= limit %>"<%= previousBtnEnabled?'':'tabindex=-1' %></a>
</li>
<% for(i=1;i<=maxPage;i++){ %>
<% if(i==1 || i==maxPage || (i>=currentPage-offset && i<=currentPage+offset)){ %>
<li class="page-item <%= currentPage==i?'active':'' %>"><a class="page-link" href="/posts?page=<%= i %>&limit=<%= limit %>"><%= i %></a></li>
<% } else if(i==2 || i==maxPage-1){ %>
<li><a class="page-link">...</a></li>
<% } %>
<% } %>
<li class="page-item <%= nextBtnEnabled?'':'disabled' %>">
<a class="page-link" href="/posts?page=<%= currentPage+1 %>&limit=<%= limit %>"<%= nextBtnEnabled?'':'tabindex=-1' %></a>
</li>
</ul>
</nav>
</div>
</div>
</body>
</html>
\ No newline at end of file
......