我应该如何向将 return 条件结果的 koa 后端发送 GET 请求?

How should I send a GET request to a koa backend that will return conditional results?

到目前为止我有这个。它有效,但我忍不住想知道是否有一些不那么骇人听闻的东西。

GET 请求:

http://localhost:3100/api/things?matches=%7B%22name%22%3A%22asdf%22%7D

decoded: matches={"name":"asdf"} -- 我基本上将数据对象用于 GET 请求,将键作为查询字符串参数名称,并将 JSON.stringify 值作为查询字符串值。

它有效....但我觉得也许我可以使用像这样的端点来更顺畅地完成它:

GET http://localhost:3100/api/things/match/:attr/:value - 但它非常有限,因为我只能有一个条件。而在上面传递整个对象时,我可以匹配多个属性。

在 Koa 方面,没有太多额外的代码(我正在使用 Thinky for RethinkDB):

  /**
   * list
   * list all things
   * @param next
   */
  ctrl.list = function *(next){
    var matches = this.request.query.matches && JSON.parse(this.request.query.matches);

    if ( matches ) {
      var result = yield Thing.orderBy({index: "createdAt"}).filter(function(doc){
        return doc('name').match(matches.name);
      });
    } else {
      var result = yield Thing.orderBy({index: "createdAt"});
    }

    this.body = result;

    yield next;
  };

如果没有查询字符串,那么它只是returns所有结果。

我走的路对吗?

我相信这是正确的方法。 Baucis, and also koa-mongo-rest 将此方法与 Mongoose 一起使用。它甚至可以更进一步。 一个例子 url 如:

/api/users?conditions={"name":"john", "city":"London"}&limit=10&skip=1&sort=-zipcode

可以通过以下代码处理:

findAll: function*(next) {
  yield next;
  var error, result;
  try {
    var conditions = {};
    var query = this.request.query;
    if (query.conditions) {
      conditions = JSON.parse(query.conditions);
    }
    var builder = model.find(conditions);
    ['limit', 'skip', 'sort'].forEach(function(key){
      if (query[key]) {
        builder[key](query[key]);
      }
    })
    result = yield builder.exec();
    return this.body = result;
  } catch (_error) {
    error = _error;
    return this.body = error;
  }
}

如果 RethinkDB 也有一个类似的库,我将不胜感激。