简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM