260722_01_ENH: pageable에 sort alias 추가

This commit is contained in:
2026-07-22 11:19:48 +09:00
parent 895eb13656
commit 2954565fc7
2 changed files with 21 additions and 4 deletions

View File

@@ -6,7 +6,10 @@ import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@@ -18,14 +21,23 @@ public final class Pageables {
}
public static Pageable of(PageRequestDto req, Class<?> sortType) {
return of(req, sortType, Function.identity());
}
public static Pageable of(PageRequestDto req, Class<?> sortType, Map<String, String> sortAliases) {
Map<String, String> aliases = (sortAliases == null) ? Map.of() : sortAliases;
return of(req, sortType, sortKey -> aliases.getOrDefault(sortKey, sortKey));
}
public static Pageable of(PageRequestDto req, Class<?> sortType, Function<String, String> sortMapper) {
int page = Math.max(req.getPageIndex(), 0);
int size = Math.max(req.getPageSize(), 1);
Sort sort = buildSort(req, sortType);
Sort sort = buildSort(req, sortType, sortMapper);
return (sort == null) ? PageRequest.of(page, size) : PageRequest.of(page, size, sort);
}
private static Sort buildSort(PageRequestDto req, Class<?> sortType) {
private static Sort buildSort(PageRequestDto req, Class<?> sortType, Function<String, String> sortMapper) {
String sortBy = req.getSortBy();
if (sortBy == null || sortBy.isBlank()) {
return null;
@@ -36,8 +48,13 @@ public final class Pageables {
: Sort.Direction.DESC;
Set<String> allowed = allowedProperties(sortType);
Function<String, String> mapper = (sortMapper == null) ? Function.identity() : sortMapper;
List<String> props = Arrays.stream(sortBy.split(","))
.map(String::trim)
.filter(s -> !s.isBlank())
.map(mapper)
.filter(Objects::nonNull)
.map(String::trim)
.filter(s -> !s.isBlank())
.collect(Collectors.toList());
@@ -74,4 +91,4 @@ public final class Pageables {
throw new IllegalStateException("Failed to introspect sortType=" + sortType.getName(), e);
}
}
}
}