com.workos.common.http.RequestConfig.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of workos Show documentation
Show all versions of workos Show documentation
The WorkOS Kotlin library provides convenient access to the WorkOS API from applications written in JVM compatible languages.
The newest version!
package com.workos.common.http
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberProperties
/**
* Configuration for HTTP Requests.
*
* @param params Query parameters appended to the URL.
* @param headers Headers of the request.
* @param data The body of the request.
*/
class RequestConfig(
val params: Map? = null,
val headers: Map? = null,
val data: Any? = null
) {
/** @suppress */
companion object {
@JvmStatic
fun builder(): RequestConfigBuilder {
return RequestConfigBuilder()
}
/** Helper method for converting data into params. */
infix fun toMap(obj: T): Map {
val params =
(obj::class as KClass).memberProperties.associate { prop: KProperty1 ->
prop.name.toSnakeCase() to
prop.get(obj)?.let { value ->
if (value::class.isData) {
toMap(value)
} else {
value.toString()
}
}
}
return params.filterValues { it != null }
}
/** Convert camel case to snake case. */
fun String.toSnakeCase() = replace(humps, "_").lowercase()
private val humps = "(?<=.)(?=\\p{Upper})".toRegex()
}
/** Builder class for creating [RequestConfig]. */
class RequestConfigBuilder {
private var params: Map = emptyMap()
private var headers: Map = emptyMap()
private var data: Any? = null
/** Set the request parameters. */
fun params(value: Map) = apply { params = value }
/** Set the request headers. */
fun headers(value: Map) = apply { headers = value as Map }
/** Set the request body. */
fun data(value: Any) = apply { data = value }
/** Creates an instance of [RequestConfig] with the given params. */
fun build(): RequestConfig {
return RequestConfig(params, headers, data)
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy