Initial Commit
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
package dev.coph.nextusweb.server.router;
|
||||
|
||||
import dev.coph.nextusweb.server.json.Json;
|
||||
import dev.coph.nextusweb.server.router.exception.BadRequestException;
|
||||
import io.netty.handler.codec.http.*;
|
||||
import io.netty.util.CharsetUtil;
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class Request {
|
||||
|
||||
private final FullHttpRequest raw;
|
||||
private final Map<String, String> pathParams;
|
||||
private Map<String, List<String>> queryParams;
|
||||
private JsonNode jsonCache;
|
||||
|
||||
public Request(FullHttpRequest raw, Map<String, String> pathParams) {
|
||||
this.raw = raw;
|
||||
this.pathParams = pathParams;
|
||||
}
|
||||
|
||||
public String pathParam(String name) {
|
||||
return pathParams.get(name);
|
||||
}
|
||||
|
||||
public String queryParam(String name) {
|
||||
if (queryParams == null) {
|
||||
queryParams = new QueryStringDecoder(raw.uri()).parameters();
|
||||
}
|
||||
var values = queryParams.get(name);
|
||||
return values == null || values.isEmpty() ? null : values.getFirst();
|
||||
}
|
||||
|
||||
public List<String> queryParams(String name) {
|
||||
if (queryParams == null) {
|
||||
queryParams = new QueryStringDecoder(raw.uri()).parameters();
|
||||
}
|
||||
return queryParams.getOrDefault(name, List.of());
|
||||
}
|
||||
|
||||
public String header(String name) {
|
||||
return raw.headers().get(name);
|
||||
}
|
||||
|
||||
public String body() {
|
||||
return raw.content().toString(CharsetUtil.UTF_8);
|
||||
}
|
||||
|
||||
public JsonNode json() {
|
||||
if (jsonCache == null) {
|
||||
try {
|
||||
byte[] bytes = new byte[raw.content().readableBytes()];
|
||||
raw.content().getBytes(raw.content().readerIndex(), bytes);
|
||||
if (bytes.length == 0) {
|
||||
jsonCache = Json.MAPPER.nullNode();
|
||||
} else {
|
||||
jsonCache = Json.MAPPER.readTree(bytes);
|
||||
}
|
||||
} catch (JacksonException e) {
|
||||
throw new BadRequestException("Invalid JSON: " + e.getOriginalMessage());
|
||||
}
|
||||
}
|
||||
return jsonCache;
|
||||
}
|
||||
|
||||
public <T> T jsonAs(Class<T> type) {
|
||||
try {
|
||||
byte[] bytes = new byte[raw.content().readableBytes()];
|
||||
raw.content().getBytes(raw.content().readerIndex(), bytes);
|
||||
return Json.MAPPER.readValue(bytes, type);
|
||||
} catch (JacksonException e) {
|
||||
throw new BadRequestException(
|
||||
"Could not deserialize body as " + type.getSimpleName() + ": " + e.getOriginalMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public HttpMethod method() {
|
||||
return raw.method();
|
||||
}
|
||||
|
||||
public String path() {
|
||||
return new QueryStringDecoder(raw.uri()).path();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user