0

I've a basic model where I would like to implement an endpoint that is capable to return subset of list back when we pass in some string param, and not sure how to go about doing it.

here is json file:

var user = [
  {"id": "1", "name": "subash", "age": "22", "occupation": "doctor"},
  {"id": "2", "name": "alex", "ip": "33", "occupation": "engineer"},
  {"id": "3", "name": "darran", "ip": "18", "occupation": "singer"}
 ];

expected endpoint

app.get('/users/:someStringParam', user.findById);

expected response

Filters/returns rows of users who's name has letter 'a'.

I've looked at app.param() method of express framework but not sure how to go about!

Simple-Solution
  • 4,209
  • 12
  • 47
  • 66
  • 1
    Use req.params.someStringParam to get the filter from that url. Then you would loop through your array and use a regex match on the names to get your filtered list. – TripWired Jun 24 '14 at 17:32

1 Answers1

1

The :parameter will be listed as part of req.params you can then use it to filter your array.

app.get('/agent/:letter', function (req, res, next) {
  var containsLetter = new RegExp(req.pararms.letter);
  res.json(users.filter(function (user) {
    return containersLetter.test(user.name);
  });
});
generalhenry
  • 17,227
  • 4
  • 48
  • 63