Create Handler Collection to provide Handlers in a centralized location to avoid localized Lambda

This commit is contained in:
Tina_Azure
2023-03-09 19:04:15 +01:00
parent f3717a2943
commit d564f4b240

View File

@ -0,0 +1,47 @@
package cavecomm;
import io.vertx.core.AsyncResult;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.web.RoutingContext;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
//Class collecting Handlers to be used instead of Complex Lmabdas
public final class HandlerCollection {
private HandlerCollection() {
}
//returns a response containing the query result as a JSON
public static void outputJSON(AsyncResult<RowSet<Row>> ar, RoutingContext rc) {
if (ar.succeeded()) {
RowSet<Row> result = ar.result();
//dump RowSet into jsonArray
JsonArray jsonArray = new JsonArray();
for (Row r : result) {
jsonArray.add(r.toJson());
}
//sets the header to json
rc.response().putHeader("Content-Type", "application/json; charset=UTF8")
.end(jsonArray.encode());
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
}
//Potentially unnecessary to exist as its own handler
public static void outputHTML(AsyncResult<RowSet<Row>> ar, RoutingContext rc) {
if (ar.succeeded()) {
RowSet<Row> result = ar.result();
//dump RowSet into jsonArray
JsonArray jsonArray = new JsonArray();
for (Row r : result) {
jsonArray.add(r.toJson());
}
//sets the header to html
rc.response().putHeader("Content-Type", "text/html; charset=UTF8")
.end(jsonArray.encodePrettily());
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
}
}