Vert.x Backend
Simplifying the HTTP verticle code
A client-side application needs a backend that exposes:
the static HTML, CSS and JavaScript content to bootstrap applications in web browsers, and
a web API, typically a HTTP/JSON service.
We simplified the HTTP verticle implementation to just cover what is needed. Starting from the RxJava version from step #8, we removed all server-side rendering code as well as the authentication and JWT token issuing code to expose a plain open HTTP/JSON interface.
Of course building a version that leverages JWT tokens and authentication makes sense for a real-world deployments, but now that we have covered these features we would rather focus on the essential bits in this part of the guide.
As an example, the apiUpdatePage
method implementation code is now:
private void apiUpdatePage(RoutingContext context) {
int id = Integer.valueOf(context.request().getParam("id"));
JsonObject page = context.getBodyAsJson();
if (!validateJsonPageDocument(context, page, "markdown")) {
return;
}
dbService.rxSavePage(id, page.getString("markdown")).subscribe(
() -> apiResponse(context, 200, null, null),
t -> apiFailure(context, t));
}
Exposed routes
The HTTP/JSON API is exposed through the sames routes as in the previous steps:
router.get("/api/pages").handler(this::apiRoot);
router.get("/api/pages/:id").handler(this::apiGetPage);
router.post().handler(BodyHandler.create());
router.post("/api/pages").handler(this::apiCreatePage);
router.put().handler(BodyHandler.create());
router.put("/api/pages/:id").handler(this::apiUpdatePage);
router.delete("/api/pages/:id").handler(this::apiDeletePage);
The front application static assets are being served from /app
, and we redirect requests to /
to the /app/index.html
static file:
router.get("/app/*").handler(StaticHandler.create().setCachingEnabled(false)); (1) (2)
router.get("/").handler(context -> context.reroute("/app/index.html"));
Disabling caching is useful in development.
By default the files are expected to be in the
webroot
package on the classpath, so the files shall be placed undersrc/main/resources/webroot
in a Maven or Gradle project.
Last but not least, we anticipate that the application will need the backend to render Markdown to HTML, so we offer a HTTP POST endpoint for this purpose:
router.post("/app/markdown").handler(context -> {
String html = Processor.process(context.getBodyAsString());
context.response()
.putHeader("Content-Type", "text/html")
.setStatusCode(200)
.end(html);
});