简体   繁体   English

如何使用Node.js和Express在REST API中实现搜索和过滤

[英]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. 我正在通过构建REST API学习和使用Node and Express。 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: 并定义了一个getAllUser函数:

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. 所有这些都工作正常,我已经可以用Postman进行测试,并且我的数据已经返回。

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: 据我了解,搜索参数将作为参数传递到URL中,例如:

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? 我将如何使用node提取这些参数,是否有要使用的特定库或要遵循的最佳实践?

Same question for filtering, or is filtering the same thing than search? 过滤是否有相同的问题,或者过滤的内容与搜索相同?

The parameters will be in req.query . 参数将在req.query

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

You can use arr.filter(callback[, thisArg]) for filtering. 您可以使用arr.filter(callback[, thisArg])进行过滤。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter https://developer.mozilla.org/zh-CN/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. 注意:在search功能中,您可能需要处理大小写,类型等问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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