Added meta response structure for http API
This commit is contained in:
parent
2be1865263
commit
4bfcc5a2ff
@ -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<TParsed, TOriginal, TResponse> {
|
||||
@ -35,19 +42,32 @@ public class HttpServer {
|
||||
}
|
||||
|
||||
public void get(String path, Function<Request, Object> 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<Request, Object> onCall) {
|
||||
Spark.post(this.buildRoute(path), (req, resp) -> this.process(() -> onCall.apply(req)));
|
||||
}
|
||||
|
||||
public <TRequest> void post(String path, Class<TRequest> clazz, RequestProvider<TRequest, Request, Object> 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<Object> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user