Skip to content

Commit a4c7d36

Browse files
committed
Added OptionalString#require and as()
1 parent e6c2193 commit a4c7d36

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: src/main/java/dev/latvian/apps/tinyserver/OptionalString.java

+28
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
package dev.latvian.apps.tinyserver;
22

3+
import dev.latvian.apps.tinyserver.http.response.error.client.BadRequestError;
4+
5+
import java.util.function.Function;
6+
37
public record OptionalString(String value) {
48
public static final OptionalString MISSING = new OptionalString(null);
59
public static final OptionalString EMPTY = new OptionalString("");
@@ -16,6 +20,14 @@ public boolean isPresent() {
1620
return value != null;
1721
}
1822

23+
public OptionalString require() {
24+
if (value == null) {
25+
throw new BadRequestError("Required value is missing!");
26+
}
27+
28+
return this;
29+
}
30+
1931
@Override
2032
public String toString() {
2133
return value == null ? "<empty>" : value;
@@ -29,6 +41,22 @@ public String asString(String def) {
2941
return value == null ? def : value;
3042
}
3143

44+
public <T> T as(Function<String, T> mapper, T def) {
45+
if (value == null) {
46+
return def;
47+
}
48+
49+
try {
50+
return mapper.apply(value);
51+
} catch (Throwable ex) {
52+
return def;
53+
}
54+
}
55+
56+
public <T> T as(Function<String, T> mapper) {
57+
return as(mapper, null);
58+
}
59+
3260
public int asInt() {
3361
return asInt(0);
3462
}

0 commit comments

Comments
 (0)