Root resource
We just remap database results in page information entry objects.
JsonObject#encode()
gives a compactString
representation of the JSON data.
Getting a page
private void apiGetPage(RoutingContext context) {
int id = Integer.valueOf(context.request().getParam("id"));
dbService.fetchPageById(id, reply -> {
JsonObject response = new JsonObject();
if (reply.succeeded()) {
JsonObject dbObject = reply.result();
if (dbObject.getBoolean("found")) {
JsonObject payload = new JsonObject()
.put("name", dbObject.getString("name"))
.put("id", dbObject.getInteger("id"))
.put("markdown", dbObject.getString("content"))
.put("html", Processor.process(dbObject.getString("content")));
response
.put("page", payload);
context.response().setStatusCode(200);
} else {
response
.put("success", false)
.put("error", "There is no page with ID " + id);
}
} else {
response
.put("success", false)
.put("error", reply.cause().getMessage());
context.response().setStatusCode(500);
}
context.response().putHeader("Content-Type", "application/json");
context.response().end(response.encode());
});
}
Creating a page
private boolean validateJsonPageDocument(RoutingContext context, JsonObject page, String... expectedKeys) {
if (!Arrays.stream(expectedKeys).allMatch(page::containsKey)) {
LOGGER.error("Bad page creation JSON payload: " + page.encodePrettily() + " from " + context.request().remoteAddress());
context.response().end(new JsonObject()
.put("success", false)
.put("error", "Bad request payload").encode());
return false;
}
return true;
}
Updating a page
The handleSimpleDbReply
method is a helper for finishing the request processing:
private void handleSimpleDbReply(RoutingContext context, AsyncResult<Void> reply) {
if (reply.succeeded()) {
context.response().setStatusCode(200);
context.response().putHeader("Content-Type", "application/json");
context.response().end(new JsonObject().put("success", true).encode());
} else {
context.response().setStatusCode(500);
context.response().putHeader("Content-Type", "application/json");
context.response().end(new JsonObject()
.put("success", false)
.put("error", reply.cause().getMessage()).encode());
}