route to record class

~5 min work
This commit is contained in:
Benedikt Galbavy 2023-12-26 17:35:01 +01:00
parent 5be9b687b5
commit ca99abe614
2 changed files with 7 additions and 14 deletions

View File

@ -2,12 +2,5 @@ package at.nanopenguin.mtcg.http;
import at.nanopenguin.mtcg.application.Service; import at.nanopenguin.mtcg.application.Service;
public class Route { public record Route(Service service, boolean hasPathVariable) {
public final Service service;
public final boolean hasPathVariable;
public Route(Service service, boolean hasPathVariable) {
this.service = service;
this.hasPathVariable = hasPathVariable;
}
} }

View File

@ -5,7 +5,7 @@ import at.nanopenguin.mtcg.application.Service;
import java.util.*; import java.util.*;
public class Router { public class Router {
private Map<HttpMethod, Map<String, Route>> routeMap = new HashMap<>(); private final Map<HttpMethod, Map<String, Route>> routeMap = new HashMap<>();
public void addRoute(final HttpMethod method, final String route, final Service service, final int pathVarPos) { public void addRoute(final HttpMethod method, final String route, final Service service, final int pathVarPos) {
Map<String, Route> map = this.routeMap.get(method); Map<String, Route> map = this.routeMap.get(method);
@ -13,7 +13,7 @@ public class Router {
this.routeMap.put(method, (map = new HashMap<>())); this.routeMap.put(method, (map = new HashMap<>()));
} }
List<String> routeComponents = new ArrayList<String>(Arrays.asList(route.split("/"))); List<String> routeComponents = new ArrayList<>(Arrays.asList(route.split("/")));
if (pathVarPos > 0) { if (pathVarPos > 0) {
routeComponents.set(pathVarPos, "{var}"); routeComponents.set(pathVarPos, "{var}");
} }
@ -35,8 +35,8 @@ public class Router {
int i = 0; int i = 0;
Route component = this.routeMap.get(method).get(routeComponents[i]); Route component = this.routeMap.get(method).get(routeComponents[i]);
System.out.println(routeComponents[i]); System.out.println(routeComponents[i]);
for (String search = routeComponents[i]; component != null && component.service == null; component = this.routeMap.get(method).get(search = String.join("/", search, routeComponents[++i]))) { for (String search = routeComponents[i]; component != null && component.service() == null; component = this.routeMap.get(method).get(search = String.join("/", search, routeComponents[++i]))) {
if (component.hasPathVariable) { if (component.hasPathVariable()) {
pathVariable = routeComponents[++i]; pathVariable = routeComponents[++i];
search = String.join("/", search, "{var}"); search = String.join("/", search, "{var}");
} }
@ -46,8 +46,8 @@ public class Router {
return null; return null;
} }
component.service.setPathVariable(pathVariable); component.service().setPathVariable(pathVariable);
return component.service; return component.service();
} }
} }