All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.schemas.LocalDateTimeSchema.kt Maven / Gradle / Ivy

There is a newer version: 0.23.0
Show newest version
package io.kform.schemas

import io.kform.TypeInfo
import io.kform.Validation
import io.kform.schemas.util.commonRestrictions
import io.kform.schemas.util.comparableBoundsRestrictions
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlinx.datetime.*

/**
 * Schema representing values of type [LocalDateTime] defined by
 * [KotlinX DateTime](https://github.com/Kotlin/kotlinx-datetime).
 */
public open class LocalDateTimeSchema(
    validations: Iterable> = emptyList(),
    override val initialValue: LocalDateTime = DEFAULT_INITIAL_VALUE
) : AbstractSimpleSchema(validations) {
    public constructor(
        vararg validations: Validation,
        initialValue: LocalDateTime = DEFAULT_INITIAL_VALUE
    ) : this(validations.toList(), initialValue)

    override val typeInfo: TypeInfo =
        TypeInfo(
            LocalDateTime::class,
            restrictions =
                commonRestrictions(validations) + comparableBoundsRestrictions(validations)
        )

    override fun assignableTo(type: KType): Boolean =
        (type.classifier as? KClass<*>)?.isInstance(DEFAULT_INITIAL_VALUE) == true

    override suspend fun fromAny(value: Any?): LocalDateTime =
        when (value) {
            is LocalDateTime -> value
            is String -> LocalDateTime.parse(value)
            else ->
                throw IllegalArgumentException("Cannot convert value '$value' to LocalDateTime.")
        }

    public companion object {
        /** Default initial value (epoch in UTC). */
        public val DEFAULT_INITIAL_VALUE: LocalDateTime =
            Instant.fromEpochMilliseconds(0).toLocalDateTime(TimeZone.UTC)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy