Skip to content

Commit b48a81f

Browse files
authored
Merge pull request #3854 from jooby-project/3853
FEATURE: Unified JSON Projection API
2 parents 218a33a + 0caf5be commit b48a81f

File tree

49 files changed

+3874
-76
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+3874
-76
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
* Jooby https://jooby.io
3+
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
4+
* Copyright 2014 Edgar Espina
5+
*/
6+
package io.jooby;
7+
8+
import java.util.*;
9+
import java.util.function.Consumer;
10+
11+
/**
12+
* A wrapper for a value and its associated {@link Projection}.
13+
*
14+
* @param <T> The value type.
15+
* @author edgar
16+
* @since 4.0.0
17+
*/
18+
public class Projected<T> {
19+
private final T value;
20+
private final Projection<T> projection;
21+
22+
private Projected(T value, Projection<T> projection) {
23+
this.value = value;
24+
this.projection = projection;
25+
}
26+
27+
@SuppressWarnings("unchecked")
28+
public static <T> Projected<T> wrap(T value) {
29+
return new Projected<T>(value, Projection.of(computeProjectionType(value)));
30+
}
31+
32+
@SuppressWarnings("rawtypes")
33+
private static Class computeProjectionType(Object value) {
34+
return switch (value) {
35+
case Set<?> col -> col.isEmpty() ? Object.class : col.iterator().next().getClass();
36+
case Collection<?> col -> col.isEmpty() ? Object.class : col.iterator().next().getClass();
37+
case Optional<?> optional -> optional.isEmpty() ? Object.class : optional.get().getClass();
38+
default -> value.getClass();
39+
};
40+
}
41+
42+
public static <T> Projected<T> wrap(T value, Projection<T> projection) {
43+
return new Projected<>(value, projection);
44+
}
45+
46+
public T getValue() {
47+
return value;
48+
}
49+
50+
public Projection<T> getProjection() {
51+
return projection;
52+
}
53+
54+
public Projected<T> include(String... paths) {
55+
projection.include(paths);
56+
return this;
57+
}
58+
59+
@SafeVarargs
60+
public final Projected<T> include(Projection.Property<T, ?>... props) {
61+
projection.include(props);
62+
return this;
63+
}
64+
65+
public <R> Projected<T> include(Projection.Property<T, R> prop, Consumer<Projection<R>> child) {
66+
projection.include(prop, child);
67+
return this;
68+
}
69+
70+
@Override
71+
public String toString() {
72+
return projection.toString();
73+
}
74+
}

0 commit comments

Comments
 (0)