|
| 1 | +package by.jprof.telegram.bot.leetcode |
| 2 | + |
| 3 | +import com.expediagroup.graphql.client.ktor.GraphQLKtorClient |
| 4 | +import com.expediagroup.graphql.client.types.GraphQLClientRequest |
| 5 | +import kotlinx.serialization.Required |
| 6 | +import kotlinx.serialization.Serializable |
| 7 | +import org.apache.logging.log4j.LogManager |
| 8 | +import java.io.Closeable |
| 9 | +import java.net.URL |
| 10 | +import kotlin.reflect.KClass |
| 11 | + |
| 12 | +class GraphQLLeetCodeClient : LeetCodeClient, Closeable { |
| 13 | + companion object { |
| 14 | + private val logger = LogManager.getLogger(GraphQLLeetCodeClient::class.java)!! |
| 15 | + } |
| 16 | + |
| 17 | + private val client = GraphQLKtorClient( |
| 18 | + url = URL("https://leetcode.com/graphql"), |
| 19 | + ) |
| 20 | + |
| 21 | + override suspend fun questionData(slug: String): Question? { |
| 22 | + val request = QuestionDataQuery(QuestionDataQuery.Variables(slug)) |
| 23 | + val response = client.execute(request) |
| 24 | + |
| 25 | + response.errors?.let { errors -> |
| 26 | + errors.forEach { error -> logger.error(error.message) } |
| 27 | + return null |
| 28 | + } |
| 29 | + |
| 30 | + return response.data?.question |
| 31 | + } |
| 32 | + |
| 33 | + override fun close() { |
| 34 | + client.close() |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +@Serializable |
| 39 | +private class QuestionDataQuery( |
| 40 | + override val variables: Variables, |
| 41 | +) : GraphQLClientRequest<QuestionData> { |
| 42 | + @Required |
| 43 | + override val query: String = """ |
| 44 | + query questionData(${"$"}slug: String!) { |
| 45 | + question(titleSlug: ${"$"}slug) { |
| 46 | + title |
| 47 | + titleSlug |
| 48 | + content |
| 49 | + isPaidOnly |
| 50 | + difficulty |
| 51 | + likes |
| 52 | + dislikes |
| 53 | + categoryTitle |
| 54 | + } |
| 55 | + } |
| 56 | + """.trimIndent() |
| 57 | + |
| 58 | + @Required |
| 59 | + override val operationName: String = "questionData" |
| 60 | + |
| 61 | + override fun responseType(): KClass<QuestionData> = QuestionData::class |
| 62 | + |
| 63 | + @Serializable |
| 64 | + data class Variables( |
| 65 | + val slug: String |
| 66 | + ) |
| 67 | +} |
| 68 | + |
| 69 | +@Serializable |
| 70 | +private data class QuestionData( |
| 71 | + val question: Question?, |
| 72 | +) |
0 commit comments