Skip to content

Commit

Permalink
Added OptionalString#require and as()
Browse files Browse the repository at this point in the history
  • Loading branch information
LatvianModder committed Nov 18, 2024
1 parent e6c2193 commit a4c7d36
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/main/java/dev/latvian/apps/tinyserver/OptionalString.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package dev.latvian.apps.tinyserver;

import dev.latvian.apps.tinyserver.http.response.error.client.BadRequestError;

import java.util.function.Function;

public record OptionalString(String value) {
public static final OptionalString MISSING = new OptionalString(null);
public static final OptionalString EMPTY = new OptionalString("");
Expand All @@ -16,6 +20,14 @@ public boolean isPresent() {
return value != null;
}

public OptionalString require() {
if (value == null) {
throw new BadRequestError("Required value is missing!");
}

return this;
}

@Override
public String toString() {
return value == null ? "<empty>" : value;
Expand All @@ -29,6 +41,22 @@ public String asString(String def) {
return value == null ? def : value;
}

public <T> T as(Function<String, T> mapper, T def) {
if (value == null) {
return def;
}

try {
return mapper.apply(value);
} catch (Throwable ex) {
return def;
}
}

public <T> T as(Function<String, T> mapper) {
return as(mapper, null);
}

public int asInt() {
return asInt(0);
}
Expand Down

0 comments on commit a4c7d36

Please sign in to comment.