File tree 1 file changed +28
-0
lines changed
src/main/java/dev/latvian/apps/tinyserver
1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 1
1
package dev .latvian .apps .tinyserver ;
2
2
3
+ import dev .latvian .apps .tinyserver .http .response .error .client .BadRequestError ;
4
+
5
+ import java .util .function .Function ;
6
+
3
7
public record OptionalString (String value ) {
4
8
public static final OptionalString MISSING = new OptionalString (null );
5
9
public static final OptionalString EMPTY = new OptionalString ("" );
@@ -16,6 +20,14 @@ public boolean isPresent() {
16
20
return value != null ;
17
21
}
18
22
23
+ public OptionalString require () {
24
+ if (value == null ) {
25
+ throw new BadRequestError ("Required value is missing!" );
26
+ }
27
+
28
+ return this ;
29
+ }
30
+
19
31
@ Override
20
32
public String toString () {
21
33
return value == null ? "<empty>" : value ;
@@ -29,6 +41,22 @@ public String asString(String def) {
29
41
return value == null ? def : value ;
30
42
}
31
43
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
+
32
60
public int asInt () {
33
61
return asInt (0 );
34
62
}
You can’t perform that action at this time.
0 commit comments