我已经实现了当前的一组路由(例如):
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": "tonysmallhands@gmail.com" } }, { "method": "POST", "call": "/api/1/customer/2", "body": { "name": "mario" } }, { "method": "GET", "call": "/api/1/company" }, { "method": "DELETE", "call": "/api/1/company/22" } ]
为此,我想知道如何调用播放框架路由器来传递这些请求?我打算使用与单元测试建议类似的方法:
@Test public void badRoute() { Result result = play.test.Helpers.routeAndCall(fakeRequest(GET, "/xx/Kiki")); assertThat(result).isNull(); }
通过进入的源代码routeAndCall(),您会发现如下所示:
routeAndCall()
/** * 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使用类加载器实例化一个调用便会出现问题吗?
Routes
您可以使用以下方法调用来路由您的虚假请求: Play.current.global.onRouteRequest。请参阅此帖子以获取完整示例:http: //yefremov.net/blog/play-batch-api/
Play.current.global.onRouteRequest