diff --git a/src/main/java/eu/mhsl/craftattack/spawn/api/HttpServer.java b/src/main/java/eu/mhsl/craftattack/spawn/api/HttpServer.java index 4fadd3e..607f3c4 100644 --- a/src/main/java/eu/mhsl/craftattack/spawn/api/HttpServer.java +++ b/src/main/java/eu/mhsl/craftattack/spawn/api/HttpServer.java @@ -8,13 +8,13 @@ import spark.Request; import spark.Spark; import java.util.function.Function; +import java.util.function.Supplier; public class HttpServer { private final ConfigurationSection apiConf = Main.instance().getConfig().getConfigurationSection("api"); protected final Gson gson = new Gson(); - public static Object nothing = ""; - + public static Object nothing = null; public HttpServer() { Spark.port(8080); @@ -23,6 +23,13 @@ public class HttpServer { Main.instance().getAppliances().forEach(appliance -> appliance.httpApi(new ApiBuilder(appliance))); } + public record Response(Status status, Object error, Object response) { + public enum Status { + FAILURE, + SUCCESS + } + } + public class ApiBuilder { @FunctionalInterface public interface RequestProvider { @@ -35,19 +42,32 @@ public class HttpServer { } public void get(String path, Function onCall) { - Spark.get(this.buildRoute(path), (req, resp) -> HttpServer.this.gson.toJson(onCall.apply(req))); + Spark.get(this.buildRoute(path), (req, resp) -> this.process(() -> onCall.apply(req))); + } + + public void rawPost(String path, Function onCall) { + Spark.post(this.buildRoute(path), (req, resp) -> this.process(() -> onCall.apply(req))); } public void post(String path, Class clazz, RequestProvider onCall) { Spark.post(this.buildRoute(path), (req, resp) -> { TRequest parsed = new Gson().fromJson(req.body(), clazz); - Object response = onCall.apply(parsed, req); - return HttpServer.this.gson.toJson(response); + return this.process(() -> onCall.apply(parsed, req)); }); } public String buildRoute(String path) { return String.format("/api/%s/%s", this.applianceName, path); } + + private String process(Supplier exec) { + HttpServer.Response response; + try { + response = new Response(Response.Status.SUCCESS, null, exec.get()); + } catch (Exception e) { + response = new Response(Response.Status.FAILURE, e, null); + } + return HttpServer.this.gson.toJson(response); + } } }