|
| 1 | +package team.yi.rsql.querydsl.handler |
| 2 | + |
| 3 | +import com.querydsl.core.types.* |
| 4 | +import com.querydsl.core.types.dsl.Expressions |
| 5 | +import cz.jirutka.rsql.parser.ast.ComparisonNode |
| 6 | +import team.yi.rsql.querydsl.* |
| 7 | +import team.yi.rsql.querydsl.operator.RsqlOperator |
| 8 | +import java.time.* |
| 9 | +import java.time.temporal.TemporalAccessor |
| 10 | + |
| 11 | +@Suppress("UNCHECKED_CAST") |
| 12 | +class TemporalAccessorFieldTypeHandler<E : Comparable<E>>( |
| 13 | + override val node: ComparisonNode, |
| 14 | + override val operator: RsqlOperator, |
| 15 | + override val fieldMetadata: FieldMetadata, |
| 16 | + override val rsqlConfig: RsqlConfig, |
| 17 | +) : TemporalFieldTypeHandler<E>(node, operator, fieldMetadata, rsqlConfig) { |
| 18 | + override fun supports(type: Class<*>?): Boolean { |
| 19 | + return if (type == null) { |
| 20 | + false |
| 21 | + } else { |
| 22 | + TemporalAccessor::class.java.isAssignableFrom(type) |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + override fun getPath(parentPath: Expression<*>?): Expression<*>? { |
| 27 | + return Expressions.dateTimePath( |
| 28 | + fieldMetadata.clazz as Class<out Comparable<*>?>, |
| 29 | + parentPath as Path<*>?, |
| 30 | + fieldMetadata.fieldSelector |
| 31 | + ) |
| 32 | + } |
| 33 | + |
| 34 | + override fun getValue(values: List<String?>, rootPath: Path<*>, fm: FieldMetadata?): Collection<Expression<out Any?>?>? { |
| 35 | + if (values.isEmpty()) return null |
| 36 | + |
| 37 | + return values.map { |
| 38 | + val value = toComparable(it, fm) ?: return null |
| 39 | + |
| 40 | + Expressions.asDateTime(value) |
| 41 | + }.toList() |
| 42 | + } |
| 43 | + |
| 44 | + @Suppress("CyclomaticComplexMethod") |
| 45 | + override fun toComparable(value: String?, fm: FieldMetadata?): Comparable<E>? { |
| 46 | + if (value.isNullOrBlank()) return null |
| 47 | + |
| 48 | + val fieldType = fm?.clazz ?: return null |
| 49 | + |
| 50 | + return runCatching { |
| 51 | + when (fieldType) { |
| 52 | + LocalDate::class.java -> LocalDate.parse(value) |
| 53 | + LocalDateTime::class.java -> LocalDateTime.parse(value) |
| 54 | + LocalTime::class.java -> LocalTime.parse(value) |
| 55 | + OffsetDateTime::class.java -> OffsetDateTime.parse(value) |
| 56 | + OffsetTime::class.java -> OffsetTime.parse(value) |
| 57 | + ZonedDateTime::class.java -> ZonedDateTime.parse(value) |
| 58 | + Duration::class.java -> Duration.parse(value) |
| 59 | + Period::class.java -> Period.parse(value) |
| 60 | + Instant::class.java -> Instant.parse(value) |
| 61 | + MonthDay::class.java -> MonthDay.parse(value) |
| 62 | + Year::class.java -> Year.parse(value) |
| 63 | + YearMonth::class.java -> YearMonth.parse(value) |
| 64 | + Month::class.java -> Month.valueOf(value) |
| 65 | + DayOfWeek::class.java -> DayOfWeek.valueOf(value) |
| 66 | + else -> null |
| 67 | + } as? Comparable<E>? |
| 68 | + }.getOrNull() |
| 69 | + } |
| 70 | +} |
0 commit comments