F
F
femalemoustache2015-11-15 15:45:38
JavaScript
femalemoustache, 2015-11-15 15:45:38

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;

In this.current I need to get the values ​​of the parameter that passes the page in the pagination. For example, for the url /posts/?page=3 this.current should be 3.
An example of using the module:
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});
});

I know that it is possible to get the parameter value inside the route handler and pass it as an argument to the Pagination constructor. I want the module to get the value itself, without having to pass it in from the code in the route handler every time.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Puma Thailand, 2015-11-15
@femalemoustache

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});

});

R
Rabinzon, 2015-11-15
@Rabinzon

router.get('/page-:page', function(req, res, next) {
      parseInt(req.params.page) 
});

req.params.page is what you need.

M
Mikhail Osher, 2015-11-15
@miraage

expressjs.com/4x/api.html#req.query

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question