zookastos
zookastos

Reputation: 935

Refactoring callback in express js

I am using express. I have multiple routers, segregated in different files -

router.post("/add", function (req, res, next) {
  if (isLoggedIn(req)) {
    nodeSdk.add(
      arg1, arg2,
      function (resp) {
        res.json(resp);
      }
    );
  }
});

router.post("/remove", function (req, res, next) {
  if (isLoggedIn(req)) {
    nodeSdk.remove(
      arg1, arg3,
      function (resp) {
        res.json(resp);
      }
    );
  }
});

I am passing same callback to nodeSdk in every router -

function(resp){
   res.json(resp);
}

Is it possible to refacor it out in a single file/place. I have too many routers, and everywhere this same callback is passed. Now I want to make the same change in every callback throughout the application. That is why I want to refactor so that in future if any change is there, it should be in one place. Thanks.

Upvotes: 1

Views: 55

Answers (1)

jfriend00
jfriend00

Reputation: 707326

First off, you could just do it like this without manually creating a callback each time:

nodeSdk.remove(arg1, arg3, res.json.bind(res));

You could even create a middleware that runs before all your routes that automatically creates an already bound version of res.json:

app.use(function(req, res, next) {
  res.jsonB = res.json.bind(res);
  next();
});

And, then you can just do this in your route handler:

nodeSdk.remove(arg1, arg3, res.jsonB);

You could also create your own wrapper function to use as a substitute that does the .bind() for you:

function nodeSdkRun(res, verb, argA, argB) {
    return nodeSdk[verb](argA, argB, res.json.bind(res));
}

And, then use it like this:

router.post("/remove", function (req, res, next) {
  if (isLoggedIn(req)) {
    nodeSdkRun(res, "remove", arg1, arg3);
  } else {
    // must send some sort of response here
    res.redirect("/login");
  }
});

Upvotes: 2

Related Questions