/**
* Created by hp-wanglihui on 2014/5/27.
*/
'use strict';
/**
*
* @param page {Number}
* @param perPage {Number}
* @param total {Number}
* @param items {dict}
* @constructor
*/
function Paginate(page, perPage, total, items){
if(!page || page <1){
page = 1;
}
if(!perPage || perPage<1){
perPage = 20;
}
if(!total || total <0){
total = 0;
}
if(!items){
items = [];
}
this.page = page;
this.perPage = perPage;
this.total = total;
this.items = items;
this.currentPageTatol = items.length;
if(this.total%this.perPage ===0){
this.pages = parseInt(this.total/this.perPage);
}else{
this.pages = parseInt(this.total /this.perPage) + 1;
}
}
/**
*
* @param page {Number}
*/
Paginate.prototype.setPage = function(page){
this.page = page;
}
/**
*
* @param perPage
*/
Paginate.prototype.setPerPage = function(perPage){
this.perPage = perPage;
}
/**
*
* @returns {boolean}
*/
Paginate.prototype.hasPrevPage = function(){
if(this.page >1){
return true;
}
return false;
}
/**
*
* @returns {number}
*/
Paginate.prototype.prevPage = function(){
if(this.page <= 1){
return 1;
}
return this.page-1;
}
/**
*
* @returns {boolean}
*/
Paginate.prototype.hasNextPage = function(){
if(this.page < this.totalPage){
return true;
}
return false;
}
/**
*
* @returns {*}
*/
Paginate.prototype.nextPage = function(){
if(this.page < this.totalPage){
return this.page+1;
}
return this.totalPage;
}
module.exports = Paginate;
プロジェクトでの使用例:
/**
*
* @param condition
* @param page
* @param perPage
* @param opt ,skip,limit...
* @param callback
* - err
* - Paginate
*/
var listBookAndPaginate = function(condition, page, perPage,opt, callback){
if(!condition){
condition = {};
}
if(!opt){
opt = {};
}
//
if(!perPage || perPage<1){
perPage = 20;
}
var skip = 0;
if(page && page >=1){
skip = (page-1) * perPage;
}
opt['skip'] = skip;
opt['limit'] = perPage;
var ep = new EventProxy();
ep.fail(callback);
ep.all('total', 'books', function(total, books){
var paginate = new Paginate(page, perPage, total, books);
callback(null, paginate);
});
//
BookSchema.count(condition,ep.done('total'));
//
BookSchema.find(condition, {}, opt, ep.done('books'));
}
コントローラからデータを取得した後の処理は以下の通りです.
var index = function(req, res, next){
BookProxy.listBookAndPaginate({},1,20,{}, function(err,paginate){
if(err){
next(err);
}else{
if(!paginate){
res.send('not paginate');
}
var page = paginate.page;
var perPage = paginate.perPage;
var total = paginate.total;
var items = paginate.items;
var currentPageTotal = paginate.currentPageTatol;
var hasNextPage = paginate.hasNextPage();
var nextPage = paginate.nextPage();
var hasPrevPage = paginate.hasPrevPage();
var prevPage = paginate.prevPage();
var pages = paginate.pages;
res.jsonp({page:page, perPage:perPage, total:total,pages:pages, items:items,currentPageTotal:currentPageTotal, hasNextPage:hasNextPage,nextPage:nextPage, hasPrevPage:hasPrevPage, prevPage:prevPage})
}
})
}