2015-06-12 20 views
0

我有這個到目前爲止。它的工作原理,但我不禁想知道是否有一些少點哈希。我應該如何發送GET請求到koa後端,它將返回條件結果?

GET請求:

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 - 但是它是非常有限的,因爲我只能有一個條件。雖然通過上面的整個對象我可以匹配多個屬性。

對事物的興亞方面,它沒有太多額外的代碼(我使用Thinky中的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; 
    }; 

如果沒有查詢字符串,那麼它只是返回所有結果。

我在正確的軌道上嗎?

+0

我不太瞭解koa,只是對你選擇的端點發表評論:如果你使用'/:attr /:value',你不會傳遞多個查詢條件:'../matches/name/asdf/color/red/prop/value ...'?似乎很尷尬。將它們解析爲查詢字符串不是更好嗎? '../ matches?name = asdf&color = red&prop = val' – laggingreflex

+0

使用查詢字符串方法的想法是我可以有多個過濾器對象像'matches = {name:'asdf'}&where = {age:18}'etc等 – chovy

+0

看來,雖然哈克,你的解決方案可能是最靈活的。你只是想在你的模型上有一個HTTP層,還是將接口限制得更多? –

回答

2

我相信這是正確的方法。這種方法被Bauciskoa-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一個類似的庫以及。

+0

還有http://thinky.io for RethinkDB – chovy

+0

好,但想想如果你需要進一步下去並指定一個名稱的屬性。讓我們說名字實際上是一個對象,它具有像完整的,尼克等屬性。你將如何開始在具有屬性的資源中指定較低層級鏈,並且在你想要屬性的屬性之一中設置爲標準。我可以看到,這隻能在您請求的資源的同一層次級別上工作,所以我沒有看到它處理更​​複雜的情況。 – PositiveGuy

+0

難道你不能只使用點符號? (請參閱http://stackoverflow.com/questions/12842632/mongodb-query-slow-with-dot-notation) –

相關問題