11package com.workos.common.http
22
3+ import kotlin.reflect.KClass
4+ import kotlin.reflect.KProperty1
5+ import kotlin.reflect.full.memberProperties
6+
37/* *
48 * Configuration for HTTP Requests.
59 *
@@ -12,44 +16,54 @@ class RequestConfig(
1216 val headers : Map <String , String >? = null ,
1317 val data : Any? = null
1418) {
15- /* *
16- * @suppress
17- */
19+ /* * @suppress */
1820 companion object {
1921 @JvmStatic
2022 fun builder (): RequestConfigBuilder {
2123 return RequestConfigBuilder ()
2224 }
25+
26+ /* * Helper method for converting data into params. */
27+ infix fun <T : Any > toMap (obj : T ): Map <String , Any ?> {
28+ val params =
29+ (obj::class as KClass <T >).memberProperties.associate { prop: KProperty1 <T , * > ->
30+ prop.name.toSnakeCase() to
31+ prop.get(obj)?.let { value ->
32+ if (value::class .isData) {
33+ toMap(value)
34+ } else {
35+ value.toString()
36+ }
37+ }
38+ }
39+
40+ return params.filterValues { it != null }
41+ }
42+
43+ /* * Convert camel case to snake case. */
44+ fun String.toSnakeCase () = replace(humps, " _" ).lowercase()
45+
46+ private val humps = " (?<=.)(?=\\ p{Upper})" .toRegex()
2347 }
2448
25- /* *
26- * Builder class for creating [RequestConfig].
27- */
49+ /* * Builder class for creating [RequestConfig]. */
2850 class RequestConfigBuilder {
2951 private var params: Map <String , String > = emptyMap()
3052
3153 private var headers: Map <String , String > = emptyMap()
3254
3355 private var data: Any? = null
3456
35- /* *
36- * Set the request parameters.
37- */
57+ /* * Set the request parameters. */
3858 fun params (value : Map <String , String >) = apply { params = value }
3959
40- /* *
41- * Set the request headers.
42- */
60+ /* * Set the request headers. */
4361 fun headers (value : Map <String , String ?>) = apply { headers = value as Map <String , String > }
4462
45- /* *
46- * Set the request body.
47- */
63+ /* * Set the request body. */
4864 fun data (value : Any ) = apply { data = value }
4965
50- /* *
51- * Creates an instance of [RequestConfig] with the given params.
52- */
66+ /* * Creates an instance of [RequestConfig] with the given params. */
5367 fun build (): RequestConfig {
5468 return RequestConfig (params, headers, data)
5569 }
0 commit comments