简体   繁体   English

使用json-server模拟搜索过滤器

[英]Mock search filter using json-server

I have routes.json and db.json 我有routes.jsondb.json

Route 路线

  "/api/*/_search?*=:searchstring": "/$1/?$2_like=:searchstring",
  "/api/*": "/$1"

DB.json DB.json

 {
  "cats": {
    "cats": []
  },
  "bats": [],
  "recordList": {
    "records": [
      {id:1, name: 'abc'},
      {id:2, name: 'def'},
      {id:3, name: 'ghi'}
    ]
  }
}

Absolutely fine fetching the record list with the above configurations. 通过上述配置,可以很好地获取记录列表。

Need to understand how to mock for the search filter call below: 需要了解如何为下面的搜索过滤器调用模拟:

http:localhost:3001/api/_search?name=abc

Updated the routes to: 将路线更新为:

{
  "/api/*": "/$1",
  "/api/_search?name_like": "/$1"
}

Following this link: https://github.com/typicode/json-server/issues/654#issuecomment-339098881 单击此链接: https : //github.com/typicode/json-server/issues/654#issuecomment-339098881

But not hitting the config URL defined, what am I doing wrong? 但是没有达到定义的配置URL,我在做什么错呢? Am I missing something here? 我在这里想念什么吗? The search term is dynamic, hence the value passed should be acceptable from a variable only but in the comment it is static. 搜索项是动态的,因此传递的值应该只能从变量接受,但在注释中是静态的。 Kindly assist with this if anyone had similar issues and resolved 如果有人遇到类似问题并解决了,请为此提供帮助

If 'abc' is searched, it should return 如果搜索到“ abc”,则应返回

{
  records: [{id: 1, name: 'abc'}]
}

You need to write your search route like this: 您需要这样编写搜索路线:

{
  "/api/records/_search?name=:searchstring": "/records/?name_like=:searchstring"
}

Or even better, you can parametrize with * to $1 replacement, thus you will be able to search for any parameter in query, and in any dataset, records or other: 甚至更好的是,您可以用*替换$1进行参数化,这样就可以在查询中以及任何数据集, records或其他中搜索任何参数:

{
  "/api/*/_search?*=:searchstring": "/$1/?$2_like=:searchstring",
  "/api/*": "/$1"
}

Afterwards your request to http://localhost:3001/api/records/_search?name=ab will be with response: 之后,您对http://localhost:3001/api/records/_search?name=ab将带有响应:

[
  {
    "id": 1,
    "name": "abc"
  }
]

Additional docs on routing . 有关路由的其他文档

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

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