|
| 1 | +package fi.espoo.evaka.nekku |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.json.JsonMapper |
| 4 | +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper |
| 5 | +import com.fasterxml.jackson.module.kotlin.readValue |
| 6 | +import fi.espoo.evaka.NekkuEnv |
| 7 | +import okhttp3.OkHttpClient |
| 8 | +import okhttp3.Request |
| 9 | +import org.springframework.stereotype.Service |
| 10 | +import okhttp3.Response |
| 11 | +import java.io.IOException |
| 12 | + |
| 13 | +@Service |
| 14 | +class NekkuService { |
| 15 | +} |
| 16 | + |
| 17 | +interface NekkuClient { |
| 18 | + |
| 19 | + fun getCustomers(): List<NekkuCustomer> |
| 20 | + |
| 21 | +} |
| 22 | + |
| 23 | +class NekkuHttpClient(private val env: NekkuEnv, private val jsonMapper: JsonMapper) : NekkuClient { |
| 24 | + val client = OkHttpClient() |
| 25 | + |
| 26 | + override fun getCustomers(): List<NekkuCustomer> = request(env, "customers") |
| 27 | + |
| 28 | + private inline fun <reified R> request(env: NekkuEnv, endpoint: String): R { |
| 29 | + val client = OkHttpClient() |
| 30 | + val fullUrl = env.url.resolve(endpoint).toString() |
| 31 | + |
| 32 | + val request = Request.Builder() |
| 33 | + .url(fullUrl) |
| 34 | + .addHeader("Authorization", "Bearer ${env.apikey.value}") |
| 35 | + .build() |
| 36 | + |
| 37 | + try { |
| 38 | + val response: Response = client.newCall(request).execute() |
| 39 | + if (response.isSuccessful) { |
| 40 | + val responseBody = response.body?.string() |
| 41 | + return jsonMapper.readValue(responseBody.toString()) |
| 42 | + } else { |
| 43 | + println("Request failed with code: ${response.code}") |
| 44 | + } |
| 45 | + } catch (e: IOException) { |
| 46 | + e.printStackTrace() |
| 47 | + } |
| 48 | + throw IllegalStateException("Request failed") |
| 49 | + } |
| 50 | + |
| 51 | +} |
| 52 | + |
| 53 | + |
| 54 | +data class NekkuCustomer(val customerNumber: String, val customerName: String) |
0 commit comments