Root resource

    1. We just remap database results in page information entry objects.

    2. JsonObject#encode() gives a compact String representation of the JSON data.

    Getting a page

    1. private void apiGetPage(RoutingContext context) {
    2. int id = Integer.valueOf(context.request().getParam("id"));
    3. dbService.fetchPageById(id, reply -> {
    4. JsonObject response = new JsonObject();
    5. if (reply.succeeded()) {
    6. JsonObject dbObject = reply.result();
    7. if (dbObject.getBoolean("found")) {
    8. JsonObject payload = new JsonObject()
    9. .put("name", dbObject.getString("name"))
    10. .put("id", dbObject.getInteger("id"))
    11. .put("markdown", dbObject.getString("content"))
    12. .put("html", Processor.process(dbObject.getString("content")));
    13. response
    14. .put("page", payload);
    15. context.response().setStatusCode(200);
    16. } else {
    17. response
    18. .put("success", false)
    19. .put("error", "There is no page with ID " + id);
    20. }
    21. } else {
    22. response
    23. .put("success", false)
    24. .put("error", reply.cause().getMessage());
    25. context.response().setStatusCode(500);
    26. }
    27. context.response().putHeader("Content-Type", "application/json");
    28. context.response().end(response.encode());
    29. });
    30. }

    Creating a page

    1. private boolean validateJsonPageDocument(RoutingContext context, JsonObject page, String... expectedKeys) {
    2. if (!Arrays.stream(expectedKeys).allMatch(page::containsKey)) {
    3. LOGGER.error("Bad page creation JSON payload: " + page.encodePrettily() + " from " + context.request().remoteAddress());
    4. context.response().end(new JsonObject()
    5. .put("success", false)
    6. .put("error", "Bad request payload").encode());
    7. return false;
    8. }
    9. return true;
    10. }

    Updating a page

    The handleSimpleDbReply method is a helper for finishing the request processing:

    1. private void handleSimpleDbReply(RoutingContext context, AsyncResult<Void> reply) {
    2. if (reply.succeeded()) {
    3. context.response().setStatusCode(200);
    4. context.response().putHeader("Content-Type", "application/json");
    5. context.response().end(new JsonObject().put("success", true).encode());
    6. } else {
    7. context.response().setStatusCode(500);
    8. context.response().putHeader("Content-Type", "application/json");
    9. context.response().end(new JsonObject()
    10. .put("success", false)
    11. .put("error", reply.cause().getMessage()).encode());
    12. }

    Deleting a page