diff --git a/src/main/java/io/seventytwo/vaadinjooq/util/VaadinJooqUtil.java b/src/main/java/io/seventytwo/vaadinjooq/util/VaadinJooqUtil.java index 32a1ae9..5d6fa80 100644 --- a/src/main/java/io/seventytwo/vaadinjooq/util/VaadinJooqUtil.java +++ b/src/main/java/io/seventytwo/vaadinjooq/util/VaadinJooqUtil.java @@ -5,12 +5,16 @@ import com.vaadin.flow.data.provider.SortDirection; import org.jooq.Field; import org.jooq.OrderField; +import org.jooq.SortField; import org.jooq.Table; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.stream.Collectors; import static java.text.MessageFormat.format; +import static org.jooq.impl.DSL.field; /** * A utility class that helps to convert between Vaadin and jOOQ @@ -39,4 +43,30 @@ public static List> orderFields(Table table, Query query) return orderFields; } + /** + * Convert a Java Record to {@link OrderField} + * + * @param recordType + * @param query The {@link Query} + * @return a {@link List} of {@link OrderField} + */ + public static List> createSortOrder(Class recordType, Query query) { + + return query.getSortOrders().stream() + .map(querySortOrder -> mapFieldsOrThrowException(recordType, querySortOrder)) + .collect(Collectors.toList()); + } + + private static SortField mapFieldsOrThrowException(Class recordType, QuerySortOrder querySortOrder) { + Arrays.stream(recordType.getRecordComponents()) + .filter(recordComponent -> !querySortOrder.getSorted().toLowerCase().equals(recordComponent.getName().toLowerCase())) + .findAny() + .orElseThrow(() -> { + throw new IllegalArgumentException(format("Field {0} is not a field of {1}", querySortOrder.getSorted(), recordType.getName())); + }); + + return querySortOrder.getDirection() == SortDirection.ASCENDING ? + field(querySortOrder.getSorted()).asc() : field(querySortOrder.getSorted()).desc(); + } + }