Is there a way to extend express.Router
?
I tried this :
class Test extends express.Router() {
};
But express throws me an error.
Any solution ?
Is there a way to extend express.Router
?
I tried this :
class Test extends express.Router() {
};
But express throws me an error.
Any solution ?
Share Improve this question edited Jan 26, 2022 at 6:43 Mohit Bhardwaj 10.1k7 gold badges40 silver badges65 bronze badges asked Feb 6, 2016 at 14:15 aukauk 1814 silver badges10 bronze badges 2 |5 Answers
Reset to default 7The right way to do it:
class Test extends express.Router {
constructor() {
super();
this.get('/', (req, res) => console.log('test'));
}
};
When you write express.Router()
(with parentheses) you already call the constructor and therefore you're trying to extend an object instead of class.
You can't do that because express.Router
is a function. I haven't found how to extend a class with the function. But you can use an approach how this http://brianflove.com/2016/03/29/typescript-express-node-js/ or use standard approach with ES2015:
import * as express from 'express';
let router = express.Router();
/* GET home page. */
router.get('/', (req, res, next) => {
res.render('index', { title: 'Express' });
});
export = router;
Maybe something like this:
function My_Router() {
return express.Router.apply(this, arguments);
}
var myRouter = new My_Router();
Excuse me, I don't know English at all. Thanks to Google Translate ...
The constructor function should return a perfect (function, in fact) object of a router. You can add to this object, whatever you want, or change it as you wish. Each interface will have a new router object, of course.
It is also necessary to determine the prototype of the constructor function. This happens in line 6.
const Router = require("express").Router;
const myRouter = function () {
const router = Router();
Object.setPrototypeOf(Router, myRouter);
router.myGet = function (path) {
router.get.call(this, arguments);
console.log("is my get function!!");
};
return router;
};
const router_custom = new myRouter();
router_custom.myGet("/", (req, res) => {
res.send("hay!!");
});
May be something like this would help
class YourController extends express.Router{
constructor(){
super()
this.get("/", (req, res)=>{
//do somthing
res.send("return something");
})
this.get("/:id", (req, res)=>{
//do something
res.send("return something);
})
}
}
module.exports = new YourController();
Use It As :
const yourExtendedRouter = require("../controllers/YourController")
router.use("/base-url", yourExtendedRouter)
Routeur
– Bek Commented Feb 6, 2016 at 17:02