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

org.http4k.lens.RequestContextKey.kt Maven / Gradle / Ivy

package org.http4k.lens

import org.http4k.core.Request
import org.http4k.core.RequestContext
import org.http4k.core.Store
import org.http4k.lens.ParamMeta.ObjectParam
import java.util.UUID

typealias RequestContextLens = BiDiLens

object RequestContextKey {
    fun  required(store: Store, name: String = UUID.randomUUID().toString()): RequestContextLens {
        val meta = Meta(true, "context", ObjectParam, name)
        val get: (Request) -> T = { target ->
            store[target].let {
                val value: T? = it[name]
                value ?: throw LensFailure(Missing(meta), target = it)
            }
        }
        val setter = { value: T, target: Request -> store[target][name] = value; target }
        return BiDiLens(meta, get, setter)
    }

    fun  optional(store: Store, name: String = UUID.randomUUID().toString()) =
        BiDiLens(Meta(false, "context", ObjectParam, name), { target -> store[target][name] },
            { value: T?, target: Request -> store[target][name] = value; target }
        )

    fun  defaulted(store: Store, default: T, name: String = UUID.randomUUID().toString()) =
        BiDiLens(Meta(false, "context", ObjectParam, name), { target -> store[target][name] ?: default },
            { value: T, target: Request -> store[target][name] = value; target }
        )
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy