pagination.js 1.28 KB
let _ = require('lodash');

class Pagination {

	constructor(url, page, totalRecords, pageSize){

        let options = {};
        let len = arguments.length;
        let args = [].slice.call(arguments);
        let _pageSize = 0;

        if(args.length && _.isPlainObject(args[len - 1])) {
            options = args.pop();
        }

        this.baseUrl = args.shift() || options.baseUrl;
        this.page = args.shift() || 1;
		this.totalRecords = args.shift() || 0;

        _pageSize = args.shift() || options.pageSize;

        this.pageSize = _pageSize || 10;
        this.totalPages = options.totalPages || 0;
		this.theme = options.theme || 'full';
		this.pageVar = options.pageVar || 'page';
		this.pageSizeVar = options.pageSizeVar || 'pageSize';

        if(!this.totalPages && this.totalRecords) {
            this.totalPages = Math.ceil(this.totalRecords / this.pageSize);
        }

        this.base = this.baseUrl + (this.baseUrl.indexOf('?') < 0 ? '?' : '&') + 
                    (_pageSize ? (this.pageSizeVar + '=' + this.pageSize + '&') : '') + 
                    this.pageVar + '=';
	}

    hasNextPage() {
        return this.page < this.totalPages;
    }

    hasPrevPage() {
        return this.page > 1;
    }

    getUrl(page) {
        return this.base + page || 1;
    }
}