gpt4 book ai didi

javascript - 我应该如何向 koa 后端发送 GET 请求以返回条件结果?

转载 作者:行者123 更新时间:2023-12-02 16:05:35 25 4
gpt4 key购买 nike

到目前为止我已经有了这个。它有效,但我忍不住想知道是否有一些不那么黑客的东西。

获取请求:

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

解码: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;
};

如果没有查询字符串,则仅返回所有结果。

我走的路正确吗?

最佳答案

我相信这是正确的方法。 Baucis 使用此方法,还有koa-mongo-rest与 Mongoose 。甚至还可以更进一步。示例网址如下:

/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 也有一个类似的库。

关于javascript - 我应该如何向 koa 后端发送 GET 请求以返回条件结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30795389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com