aboutsummaryrefslogtreecommitdiff
path: root/shared/src/commonMain/kotlin/mx/trackermap/TrackerMap/client/infrastructure/ApiClient.kt
blob: 0f1d7da9d8ce4c93274b7fc03c3e866295b63bf7 (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
package mx.trackermap.TrackerMap.client.infrastructure

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.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.util.*
import java.io.File

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 ApiXmlMediaType = "application/xml"

        val client: HttpClient = HttpClient(CIO) {
            install(JsonFeature)
        }

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

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

    protected inline fun <reified T> fillRequest(requestBuilder: HttpRequestBuilder, content: T, mediaType: String = ApiJsonMediaType) {
        when {
            content is File -> TODO("i don't know what to do here.")
            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 == 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(requestConfig.path.trimStart('/'))

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

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

        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
            }
        }

        headers.forEach { header ->
            request.headers[header.key] = header.value
        }

        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()
            )
        }
    }
}