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

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

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

import io.kform.*

/**
 * Abstract schema representing simple (non-parent) values of type [T].
 *
 * **Note**: schemas representing non-primitive values extending this class might need to implement
 * [clone], as the default implementation might not be desirable when values are mutable.
 */
public abstract class AbstractSimpleSchema(validations: Iterable>) : Schema {
    override val validations: List> = validations.toList()

    // Default implementation which is valid for non-mutable values; simple schemas holding
    // mutable values should override this function
    override suspend fun clone(value: T): T = value

    @Suppress("UNCHECKED_CAST") public open suspend fun fromAny(value: Any?): T = clone(value as T)

    override suspend fun init(path: AbsolutePath, fromValue: Any?, eventsBus: SchemaEventsBus): T {
        val newValue = fromAny(fromValue)
        eventsBus.emit(ValueEvent.Init(newValue, path, this))
        return newValue
    }

    override suspend fun change(
        path: AbsolutePath,
        value: T,
        intoValue: Any?,
        eventsBus: SchemaEventsBus
    ): T {
        val newValue = fromAny(intoValue)
        if (value != newValue) {
            eventsBus.emit(ValueEvent.Change(value, newValue, path, this))
            return newValue
        }
        return value
    }

    override suspend fun destroy(path: AbsolutePath, value: T, eventsBus: SchemaEventsBus): T {
        eventsBus.emit(ValueEvent.Destroy(value, path, this))
        return value
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy