How can I subclass the Router?

Hello,
I am effectively trying to do the following:

var Router = require('express').Router;
var util = require('util');

function MyRouter(){
   return Router.apply(this, arguments);
}
util.inherits(MyRouter, Router);
MyRouter.prototype.get = function(){
   //do some fancy shenanigans
   MyRouter.super_.get.apply(this, arguments);
}

This however is not working and I believe is linked to #2413.

I apologize if this is the wrong place for this question, but, I pose it here since the following was stated in the thread:

If you are not happy you cannot extend Express’s router’s prototype, then either use the router module

More over, I couldn’t help but feel like creating a custom Router should be documented.

Note: I have tried many, MANY combinations of inheritance but the above was the most simple/standard

Author: Fantashit

1 thought on “How can I subclass the Router?

  1. Here is a simple example, using what you provided above:

    var express = require('express')
    var request = require('supertest')
    var Router = require('router')
    var util = require('util')
    
    function MyRouter() {
        return Router.call(this, arguments)
    }
    util.inherits(MyRouter, Router)
    MyRouter.prototype.get = function(){
       console.log('do some fancy shenanigans')
       MyRouter.super_.prototype.get.apply(this, arguments)
    }
    
    var router = new MyRouter()
    var app = express()
    app.use(router)
    router.get('/', function (req, res) {
        res.send('hello, world!')
    })
    
    request(app)
    .get('/')
    .expect(200, 'hello, world!', function (err) {
        if (err) throw err
        console.log('success')
    })

    More over, I couldn’t help but feel like creating a custom Router should be documented.

    This is a great suggestion! Since Express 4.x does not allow you to create a custom router, I’m not sure where such documentation could ever live in the Express docs. Perhaps one day when 5.0 is released and there are Express 5.0 docs, it could probably live there 🙂

    Documentation requests can be filed at https://github.com/strongloop/expressjs.com for our docs team!

Comments are closed.