Answer the question
In order to leave comments, you need to log in
How to access get-parameter inside a module?
I am writing a simple pagination module for an Express.js application:
var config = require('../config');
function Pagination(options) {
this.param = options.param || 'page';
//this.current = ?
this.perPage = options.perPage || config.perPage;
this.numPages = Math.ceil(options.numRows / this.perPage);
this.prevPage = null;
this.nextPage = null;
this.hasPrevPage = function() {
return (this.current > 1 && this.numPages);
}
this.hasNextPage = function() {
return (this.numPages > this.current);
}
if (this.hasPrevPage()) {
this.prevPage = this.current - 1;
}
if (this.hasNextPage()) {
this.nextPage = this.current + 1;
}
}
module.exports = Pagination;
var express = require('express');
var Pagination = require('../core/pagination');
var config = require('../config');
var router = express.Router();
router.get('/', function(req, res) {
//...
pagination = new Pagination({
numRows: dbresult.count
});
res.render('posts', {posts: dbresult.rows, pagination: pagination});
});
Answer the question
In order to leave comments, you need to log in
If I understand your idea correctly, then you need to implement the middleware
by implementing it globally for all requests or where you specify it explicitly,
if you wrap the current one it will turn out something like this:
function pagination(req, res, next) {
var page = parseInt(req.params.page) || 1;
req.pagination = new Pagination ({
page: page,
});
}
router.get('/', pagination,function(req, res) {
....
req.pagination.numRows = dbresult.count;
res.render('posts', {posts: dbresult.rows, pagination: req.pagination});
});
router.get('/page-:page', function(req, res, next) {
parseInt(req.params.page)
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question