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

commonMain.io.konform.validation.ValidationResult.kt Maven / Gradle / Ivy

There is a newer version: 0.10.0
Show newest version
package io.konform.validation

import io.konform.validation.kotlin.Path

public interface ValidationError {
    public val dataPath: String
    public val message: String
}

internal data class PropertyValidationError(
    override val dataPath: String,
    override val message: String,
) : ValidationError {
    override fun toString(): String = "ValidationError(dataPath=$dataPath, message=$message)"
}

@Deprecated("Replace with directly using List", ReplaceWith("List"))
public interface ValidationErrors : List

public sealed class ValidationResult {
    /** Get the validation errors at a specific path. Will return null for a valid result. */
    public abstract operator fun get(vararg propertyPath: Any): List?

    /**  If this is a valid result, returns the result of applying the given [transform] function to the value. Otherwise, return the original error. */
    public inline fun  map(transform: (T) -> R): ValidationResult =
        when (this) {
            is Valid -> Valid(transform(this.value))
            is Invalid -> this
        }

    public abstract val errors: List

    /**
     * Returns true if the [ValidationResult] is [Valid].
     */
    public val isValid: Boolean =
        when (this) {
            is Invalid -> false
            is Valid -> true
        }
}

public data class Invalid(
    internal val internalErrors: Map>,
) : ValidationResult() {
    override fun get(vararg propertyPath: Any): List? = internalErrors[Path.toPath(*propertyPath)]

    override val errors: List by lazy {
        internalErrors.flatMap { (path, errors) ->
            errors.map { PropertyValidationError(path, it) }
        }
    }

    override fun toString(): String = "Invalid(errors=$errors)"
}

public data class Valid(
    val value: T,
) : ValidationResult() {
    // This will not be removed as long as ValidationResult has it, but we still deprecate it to warn the user
    // that it is nonsensical to do.
    @Deprecated("It is not useful to index a valid result, it will always return null", ReplaceWith("null"))
    override fun get(vararg propertyPath: Any): List? = null

    // This will not be removed as long as ValidationResult has it, but we still deprecate it to warn the user
    // that it is nonsensical to do.
    @Deprecated("It is not useful to call errors on a valid result, it will always return an empty list.", ReplaceWith("emptyList()"))
    override val errors: List
        get() = emptyList()
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy