5

I have two GET routes for get stores but, one route is for get all stores and the other route is for get just nearby stores.

1) The url request for get all stores is as follows:

http://mydomain/stores

2) The url for get all nearby stores:

http://mydomain/stores?lat={lat}&lng={lng}&radius={radius}

The question is:

How can I map those urls properly in Express, in a way to redirect each route to the corresponding method?

app.get('/stores', store.getAll);

app.get('/stores', store.getNear);
vitorvigano
  • 697
  • 2
  • 8
  • 18

1 Answers1

12
app.get('/stores', function(req, res, next){
  if(req.query['lat'] && req.query['lng'] && req.query['radius']){
    store.getNear(req, res, next);
  } else {
    store.getAll(req, res, next)
  };
});

edit - a second way to do it:

store.getNear = function(req, res, next){
  if(req.query['lat'] && req.query['lng'] && req.query['radius']){
    // do whatever it is you usually do in getNear
  } else {  // proceed to the next matching routing function
    next()
  };
}
store.getAll = function(req, res, next){
  // do whatever you usually do in getAll
}

app.get('/stores', store.getNear, store.getAll)
// equivalent:
// app.get('/stores', store.getNear)
// app.get('/stores', store.getAll)
Plato
  • 10,812
  • 2
  • 41
  • 61
  • note that this will fail if lat/lng/radius are zero since that is falsy; if that's a problem you can explicitly test against `undefined` – Plato Jan 29 '14 at 18:01
  • My idea was to avoid using if but, if there isn't another way, it's ok! – vitorvigano Jan 30 '14 at 13:47
  • i posted an alternative way, but why would you expect to be able to run different functions for the same route depending on circumstances without an `if` somewhere? – Plato Jan 30 '14 at 21:01
  • 1
    imo the most elegant way is to not use the same url for two things... i would have a path `/stores/all` and another path `/stores/near?lat=...` and put the if statement in the front-side code so the user's actions send an appropriate request – Plato Jan 30 '14 at 23:10