|
| 1 | +package by.jprof.telegram.bot.english.urban_dictionary |
| 2 | + |
| 3 | +import io.ktor.client.HttpClient |
| 4 | +import io.ktor.client.call.body |
| 5 | +import io.ktor.client.engine.apache.Apache |
| 6 | +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation |
| 7 | +import io.ktor.client.request.get |
| 8 | +import io.ktor.client.request.parameter |
| 9 | +import io.ktor.client.request.url |
| 10 | +import io.ktor.serialization.kotlinx.json.json |
| 11 | +import java.io.Closeable |
| 12 | +import kotlinx.serialization.Serializable |
| 13 | +import kotlinx.serialization.json.Json |
| 14 | + |
| 15 | +class KtorUrbanDictionaryClient( |
| 16 | + private val baseUrl: String = "https://api.urbandictionary.com/v0" |
| 17 | +) : UrbanDictionaryClient, Closeable { |
| 18 | + private val client = HttpClient(Apache) { |
| 19 | + install(ContentNegotiation) { |
| 20 | + json( |
| 21 | + Json { |
| 22 | + ignoreUnknownKeys = true |
| 23 | + } |
| 24 | + ) |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + override suspend fun define(term: String): Collection<Definition> = |
| 29 | + client.get { |
| 30 | + url("$baseUrl/define") |
| 31 | + parameter("term", term) |
| 32 | + }.body<UrbanDictionaryResponse>().list |
| 33 | + |
| 34 | + override suspend fun random(): Collection<Definition> = |
| 35 | + client.get { |
| 36 | + url("$baseUrl/random") |
| 37 | + }.body<UrbanDictionaryResponse>().list |
| 38 | + |
| 39 | + override fun close() { |
| 40 | + client.close() |
| 41 | + } |
| 42 | + |
| 43 | + @Serializable |
| 44 | + private data class UrbanDictionaryResponse( |
| 45 | + val list: List<Definition> |
| 46 | + ) |
| 47 | +} |
0 commit comments