2014-03-25 77 views
1

我當前的一組(例如)實現的路線:批次的HTTP請求中播放框架

GET  /api/:version/:entity    my.controllers.~~~~~ 
GET  /api/:version/:entity/:id   my.controllers.~~~~~ 
POST /api/:version/:entity    my.controllers.~~~~~ 
POST /api/:version/:entity/:id   my.controllers.~~~~~ 
DELETE /api/:version/:entity    my.controllers.~~~~~ 

POST /api/:version/search/:entity  my.controllers.~~~~~ 

他們做工精美。現在讓我們說我想爲同一個API實現「批處理端點」。它應該是這個樣子:

POST /api/:version/batch     my.controllers.~~~~~ 

和身體應該是這樣的:

[ 
    { 
     "method": "POST", 
     "call": "/api/1/customer", 
     "body": { 
      "name": "antonio", 
      "email": "[email protected]" 
     } 
    }, 
    { 
     "method": "POST", 
     "call": "/api/1/customer/2", 
     "body": { 
      "name": "mario" 
     } 
    }, 
    { 
     "method": "GET", 
     "call": "/api/1/company" 
    }, 
    { 
     "method": "DELETE", 
     "call": "/api/1/company/22" 
    } 
] 

爲了做到這一點,我想知道我怎麼能叫戲的框架路由器傳遞這些請求?我打算建議什麼單元測試使用的是類似的東西:通過進入的routeAndCall()源代碼

@Test 
public void badRoute() { 
    Result result = play.test.Helpers.routeAndCall(fakeRequest(GET, "/xx/Kiki")); 
    assertThat(result).isNull(); 
} 

,你會發現這樣的事情:

/** 
* Use the Router to determine the Action to call for this request and executes it. 
* @deprecated 
* @see #route instead 
*/ 
@SuppressWarnings(value = "unchecked") 
public static Result routeAndCall(FakeRequest fakeRequest) { 
    try { 
     return routeAndCall((Class<? extends play.core.Router.Routes>)FakeRequest.class.getClassLoader().loadClass("Routes"), fakeRequest); 
    } catch(RuntimeException e) { 
     throw e; 
    } catch(Throwable t) { 
     throw new RuntimeException(t); 
    } 
} 

/** 
* Use the Router to determine the Action to call for this request and executes it. 
* @deprecated 
* @see #route instead 
*/ 
public static Result routeAndCall(Class<? extends play.core.Router.Routes> router, FakeRequest fakeRequest) { 
    try { 
     play.core.Router.Routes routes = (play.core.Router.Routes)router.getClassLoader().loadClass(router.getName() + "$").getDeclaredField("MODULE$").get(null); 
     if(routes.routes().isDefinedAt(fakeRequest.getWrappedRequest())) { 
      return invokeHandler(routes.routes().apply(fakeRequest.getWrappedRequest()), fakeRequest); 
     } else { 
      return null; 
     } 
    } catch(RuntimeException e) { 
     throw e; 
    } catch(Throwable t) { 
     throw new RuntimeException(t); 
    } 
} 

所以我的問題是:用Play來做這件事(我不反對混合Scala和Java去實現它)比使用上面的代碼要少一些「黑客」方法?我也想給出的選擇,並行或按順序執行批處理調用...我想使用類加載器只實例化一個Routes會有問題嗎?

回答

0

您可以使用WS API,但個人而言,我只是創建一個私有方法來收集數據並從「單一」和「批量」操作中使用它們 - 它的速度肯定會更快。

+0

我確實考慮過這個(在絕望中)。我想避免必須向我的服務器發送額外的HTTP請求...因爲批處理端點的一大優點是隻需一個HTTP請求就能執行大量的調用。 –

+0

因此,只需採用第二種建議的方法,即可在您的「批次」操作中首先收集即。要獲取的id列表,然後執行單個查詢並生成返回對象 – biesior

+0

您能更具體嗎?我在批處理的一般原則方面沒有任何問題......我唯一的問題是我不知道如何從代碼中調用播放框架路由。 –

相關問題