aboutsummaryrefslogtreecommitdiff
path: root/shared/src/commonMain/kotlin/mx/trackermap/TrackerMap/client/infrastructure/ApiClient.kt
blob: 606fef063773fd59a63bb10bb937a69166c31d33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package mx.trackermap.TrackerMap.client.infrastructure

import com.russhwolf.settings.Settings
import com.russhwolf.settings.string
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.KotlinxSerializer
import io.ktor.client.features.logging.DEFAULT
import io.ktor.client.features.logging.LogLevel
import io.ktor.client.features.logging.Logger
import io.ktor.client.features.logging.Logging
import io.ktor.client.request.*
import io.ktor.client.request.forms.FormDataContent
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.util.*
import mx.trackermap.TrackerMap.client.apis.ACCESS_TOKEN_KEY
import kotlinx.serialization.json.Json as KotlinJson

open class ApiClient(val baseUrl: String) {
    companion object {
        protected const val ApiContentType = "Content-Type"
        protected const val ApiAccept = "Accept"
        protected const val ApiJsonMediaType = "application/json"
        protected const val ApiFormDataMediaType = "multipart/form-data"
        protected const val ApiFormURLType = "application/x-www-form-urlencoded"
        protected const val ApiXmlMediaType = "application/xml"

        val client: HttpClient = HttpClient(CIO) {
            install(JsonFeature) {
                serializer = KotlinxSerializer(
                    KotlinJson {
                        ignoreUnknownKeys = true
                    }
                )
            }
            install(Logging) {
                logger = Logger.DEFAULT
                level = LogLevel.ALL
            }
            engine {
                requestTimeout = 20_000
            }
        }

        val defaultHeaders: Map<String, String> =
            mapOf(
                ApiContentType to ApiJsonMediaType,
                ApiAccept to ApiJsonMediaType
            )

        val jsonHeaders: Map<String, String> =
            mapOf(
                ApiContentType to ApiJsonMediaType,
                ApiAccept to ApiJsonMediaType
            )
    }

    var token: String = ""

    init {
        val settings = Settings()
        token = settings.getString(ACCESS_TOKEN_KEY, "")
    }

    protected inline fun <reified T> fillRequest(
        requestBuilder: HttpRequestBuilder,
        content: T,
        mediaType: String = ApiJsonMediaType
    ) {
        when {
            mediaType == ApiFormDataMediaType && content is Map<*, *> -> {
                val parametersBuilder = ParametersBuilder()
                content.forEach { map ->
                    if (map.key is String && map.value is String) {
                        parametersBuilder[map.key as String] = map.value as String
                    }
                }
                parametersBuilder.build()
                requestBuilder.contentType(ContentType.MultiPart.FormData)
                requestBuilder.body = parametersBuilder
            }
            mediaType == ApiJsonMediaType -> {
                requestBuilder.contentType(ContentType.Application.Json)
                if (content != null) {
                    requestBuilder.body = content
                }
            }
            mediaType == ApiFormURLType && content is Map<*, *> -> {
                val parametersBuilder = ParametersBuilder()
                content.forEach { item ->
                    parametersBuilder[item.key as String] = item.value as String
                }
                requestBuilder.body = FormDataContent(parametersBuilder.build())
            }
            mediaType == ApiXmlMediaType -> TODO("xml not currently supported.")

            // TODO: this should be extended with other serializers
            else -> TODO("requestBody currently only supports JSON body and File body.")
        }
    }

    protected suspend inline fun <reified T : Any?> request(
        requestConfig: RequestConfig,
        body: Any? = null
    ): ApiInfrastructureResponse<T?> {
        val httpUrl: Url
        try {
            httpUrl = Url(baseUrl)
        } catch (e: URLDecodeException) {
            throw IllegalStateException("baseUrl is invalid.")
        }

        val urlBuilder = URLBuilder(httpUrl)
            .path("${httpUrl.encodedPath.trimStart('/')}${requestConfig.path}")

        requestConfig.query.forEach { query ->
            query.value.forEach { queryValue ->
                urlBuilder.parameters.append(query.key, queryValue)
            }
        }

        val url = urlBuilder.build()
        val headers = defaultHeaders + requestConfig.headers

        if (headers[ApiContentType] ?: "" == "") {
            throw IllegalStateException("Missing Content-Type header. This is required.")
        }

        if (headers[ApiAccept] ?: "" == "") {
            throw IllegalStateException("Missing Accept header. This is required.")
        }

        // TODO: support multiple contentType,accept options here.
        val contentType = (headers[ApiContentType] as String).substringBefore(";").lowercase()
        val accept = (headers[ApiAccept] as String).substringBefore(";").lowercase()

        val request = HttpRequestBuilder()
        request.url(url)
        request.accept(ContentType.parse(accept))

        when (requestConfig.method) {
            RequestMethod.DELETE -> {
                request.method = HttpMethod.Delete
            }
            RequestMethod.GET -> {
                request.method = HttpMethod.Get
            }
            RequestMethod.HEAD -> {
                request.method = HttpMethod.Head
            }
            RequestMethod.PATCH -> {
                request.method = HttpMethod.Patch
                fillRequest(request, body, contentType)
            }
            RequestMethod.PUT -> {
                request.method = HttpMethod.Put
                fillRequest(request, body, contentType)
            }
            RequestMethod.POST -> {
                request.method = HttpMethod.Post
                fillRequest(request, body, contentType)
            }
            RequestMethod.OPTIONS -> {
                request.method = HttpMethod.Options
            }
        }

        if (token.isNotEmpty()) {
            request.headers["Cookie"] = token
        }
        val response: HttpResponse = client.request(request)

        // TODO: handle specific mapping types. e.g. Map<int, Class<?>>
        when (response.status.value) {
            in 300..399 -> return Redirection(
                response.status.value,
                response.headers.toMap()
            )
            in 100..199 -> return Informational(
                response.status.description,
                response.status.value,
                response.headers.toMap()
            )
            in 200..299 -> return Success(
                response.receive(),
                response.status.value,
                response.headers.toMap()
            )
            in 400..499 -> return ClientError(
                response.receive(),
                response.status.value,
                response.headers.toMap()
            )
            else -> return ServerError(
                null,
                response.receive(),
                response.status.value,
                response.headers.toMap()
            )
        }
    }
}