Himmators
Himmators

Reputation: 15006

Apply to all existing routes?

I have to routes that I currently do like this:

app.all('*', passport.authenticate('facebook-token',  { session: false }));

//Here goes specific routes.

app.get('/user/me',
    (req, res, next) => {
        next();
});

app.get('/user/makeRider',
    (req, res, next) => {
        req.user.user.makeRider(req.query)
            .then((user) => {
                next();
            });
    }
);

app.all('*', (req, res) => {
    req.user.user.full().then((fulluser) => {
        res.json({
            user: fulluser,
            params: req.query
        });
    });
});

They are responsible for authentification and output in my REST-api. The problem with these routes is that they make all routes valid, never throwing 404:s. Is there a better way of doing this, without adding the functions to every route?

Upvotes: 0

Views: 29

Answers (1)

robertklep
robertklep

Reputation: 203359

This is not a setup that is common to Express (Restify has an option where you can call next() to transfer the request to a specific route, which would be your output handler, but that has its limitations as well).

Here's a possible workaround.

First, declare a output middleware:

let outputMiddleware = (req, res) => {
  req.user.user.full().then((fulluser) => {
    res.json({
      user: fulluser,
      params: req.query
    });
  });
};

Next, store a reference to the Passport middleware:

let authenticateMiddleware = passport.authenticate('facebook-token', { session: false });

And create a wrapper function to chain all middleware functions together:

let chain = (fn) => [ authenticateMiddleware, fn, outputMiddleware ];

Lastly, declare your routes like this:

app.get('/user/me', chain((req, res, next) => {
  next();
}));

What this does is basically create route handlers that look like this:

app.get('/user/me', [
  passport.authenticate(...),
  (req, res, next) => { ...; next() },
  (req, res) => { ...; res.json(...) }
]);

Upvotes: 1

Related Questions