Last active
April 23, 2020 08:42
-
-
Save saschpe/84b31cb88005c0b72f8239c8f5584308 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Api( | |
userAgent: String, | |
val apiKey: String | |
) { | |
val client = HttpClient { | |
install(JsonFeature) { | |
serializer = KotlinxSerializer(Json.nonstrict) | |
} | |
install(Logging) { | |
logger = Logger.DEFAULT | |
level = LogLevel.HEADERS | |
} | |
install(UserAgent) { agent = userAgent } | |
} | |
fun fullUrl(path: String) = "$API_URL$API_BASE_PATH$path" | |
suspend inline fun <reified T> get( | |
path: String, | |
block: HttpRequestBuilder.() -> Unit = {} | |
): T = client.get(fullUrl(path)) { parameter("key", apiKey); block() } | |
suspend inline fun <reified T> put( | |
path: String, | |
block: HttpRequestBuilder.() -> Unit = {} | |
): T = client.put(fullUrl(path)) { parameter("key", apiKey); block() } | |
suspend inline fun <reified T> post( | |
path: String, | |
block: HttpRequestBuilder.() -> Unit = {} | |
): T = client.post(fullUrl(path)) { parameter("key", apiKey); block() } | |
suspend inline fun <reified T> delete( | |
path: String, | |
block: HttpRequestBuilder.() -> Unit = {} | |
): T = client.delete(fullUrl(path)) { parameter("key", apiKey); block() } | |
companion object { | |
private const val API_URL = "https://example.com/" | |
private const val API_BASE_PATH = "v01/" | |
} | |
} | |
fun HttpRequestBuilder.headerAuthorization(token: String) = | |
header(HttpHeaders.Authorization, "Bearer $token") | |
fun HttpRequestBuilder.headerContentTypeJson() = | |
header(HttpHeaders.ContentType, ContentType.Application.Json) | |
fun HttpRequestBuilder.headerAcceptJson() = | |
header(HttpHeaders.Accept, ContentType.Application.Json) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment