How to implement search and filtering in a REST API with nodejs and express

30,663

The parameters will be in req.query.

{ 'firstName': 'john', 'age': '30' }

You can use arr.filter(callback[, thisArg]) for filtering.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Something like this:

function search(query) {
  return function(element) {
    for(var i in query) {
      if(query[i] != element[i]) {
        return false;
      }
    }
    return true;
  }
}

exports.search = function(query) {
  return users.filter(search(query));
}

And in your route:

router.get('/users', function(req, res, next) {
  return res.json({ users: users.search(req.query) });
});

Note: In the search function you may need to do something about case, type, etc.

Share:
30,663
dukable
Author by

dukable

Updated on September 30, 2020

Comments

  • dukable
    dukable over 3 years

    I am learning and playing around with Node and Express by building a REST API. I don't have any DB to store data, I do everything in-memory.

    Let's say I have an array of users:

    var users = [{"id": "1", "firstName": "John", "lastName": "Doe"}];
    

    and defined a getAllUser function:

    exports.getAllUser = function(page, items) {
      page = (page < 1 ? 1 : page) || 1;
      items = (items < 1 ? 5 : items) || 5;
      var indexStart, indexEnd;
      indexStart = (page - 1) * items;
      indexEnd = indexStart + items;
      return users.slice(indexStart, indexEnd);
    };
    

    and defined a route:

    router.get('/users', function(req, res, next) {
      var page = req.query.page;
          items = req.query.items;
      page = page !== 'undefined' ? parseInt(page, 10) : undefined;
      items = items !== 'undefined' ? parseInt(items, 10) : undefined;
    
      res.status(200).json({ users: users.search(page, items) });
    });
    

    All of this works fine, I have been able to test it with Postman and my data is being returned.

    My question is, how to implement search and filtering?

    From what I understand, search parameters will be passed in the URL as parameters, for example:

    http://localhost:8080/api/users/firstName=john&age=30
    

    How would I extract those parameters with node, and is there a specific lib to use or best practices to follow?

    Same question for filtering, or is filtering the same thing than search?

  • dukable
    dukable over 9 years
    Thanks! I have edited my initial post to reflect how I am dealing with paging right now. I am really lacking some good practice example. I am trying to gather how to do this and that but when it's time to mix everything together I am kind of lost. Should I just pass the page, items AND query parameters all together to the getAllUser method?