John
John

Reputation: 1123

Override express route handler

I'm trying to redefine a express route handler

I have something like

var x = {
    handle: function(req, res){
        res.send("first");
    }
}
app.post("/handle", x.handle);

setTimeout(function(){
    x.handle = function(req, res){
        res.send("second");
    }
}, 2000)

but this doesn't change the way that route handles requests. How can I achieve something like this?

Upvotes: 2

Views: 1180

Answers (2)

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

A simplest fix is to ensure x.handle is always retrieved. In your approach, the function reference is retrieved once, when you attach it but then when you set the reference to point to another function, the post handler still points to the old one.

Attach then

app.post("/handle", (req, res) => x.handle(req, res) );

This method always asks x for current value of the handle method and you are free to reattach it to anything you want.

Upvotes: 2

Derick Bailey
Derick Bailey

Reputation: 72868

why it doesn't work

when you pass x.handle into a method, as a callback, you are not passing a reference to x at all. you are only passing handle around.

later, when you change x.handle, you are changing the handle method for x as expected. but, the previous reference to x.handle as a parameter to your post method is unchanged, because this call to post knows nothing about x. it only knows about the handle method that you passed in.

how to fix it

there are a lot of ways to fix this, depending on how you really want to handle things.

if you just need a timeout, then something like this would work:


var count = 1;
app.post("/handle", function(req, res){

  if (count === 1){
    setTimeout(function(){
      count += 1;
    }, 2000);
    // do the first thing here
  } else {
    // do the second thing here
  }  

});

if you don't need the timeout, you could just increment the count

again, there are a lot of ways to do this... but you will have to include the logic of deciding which one to do, inside of the route handler function directly.

Upvotes: 0

Related Questions