This commit is contained in:
Erik C. Thauvin 2021-05-08 21:45:06 -07:00
parent 06020655a7
commit aac0d273cf

View file

@ -49,15 +49,14 @@ open class CryptoPrice(val base: String, val currency: String, val amount: Doubl
private const val COINBASE_API_URL = "https://api.coinbase.com/v2/" private const val COINBASE_API_URL = "https://api.coinbase.com/v2/"
@JvmStatic @JvmStatic
@Throws(CryptoException::class)
fun String.toPrice(): CryptoPrice { fun String.toPrice(): CryptoPrice {
val json = JSONObject(this) val json = JSONObject(this)
if (json.has("data")) { if (json.has("data")) {
val data = json.getJSONObject("data") with(json.getJSONObject("data")) {
return CryptoPrice( return CryptoPrice(getString("base"), getString("currency"), getString("amount").toDouble()
data.getString("base"),
data.getString("currency"),
data.getString("amount").toDouble()
) )
}
} else { } else {
throw CryptoException("Missing JSON data.") throw CryptoException("Missing JSON data.")
} }
@ -112,10 +111,7 @@ open class CryptoPrice(val base: String, val currency: String, val amount: Doubl
@JvmOverloads @JvmOverloads
@Throws(CryptoException::class) @Throws(CryptoException::class)
fun marketPrice(base: String, currency: String = "USD", date: LocalDate? = null): CryptoPrice { fun marketPrice(base: String, currency: String = "USD", date: LocalDate? = null): CryptoPrice {
val params = mutableMapOf<String, String>() val params = if (date != null) mapOf("date" to "$date") else emptyMap()
if (date != null) {
params.put("date", "$date")
}
val body = apiCall(listOf("prices", "$base-$currency", "spot"), params) val body = apiCall(listOf("prices", "$base-$currency", "spot"), params)
return body.toPrice() return body.toPrice()
} }