diff --git a/esplora-api/src/lib.rs b/esplora-api/src/lib.rs index 2553c60..c765e4a 100644 --- a/esplora-api/src/lib.rs +++ b/esplora-api/src/lib.rs @@ -1,30 +1,31 @@ //! Esplora API //! //! Author: Vincenzo Palazzo -use std::io; - use curl::easy::Easy; +use curl::Error; use serde_json as json; +type Result = core::result::Result; + pub struct EsploraAPI { base_url: String, } impl EsploraAPI { /// Create a new instance of the esplora API client. - pub fn new(url: &str) -> io::Result { + pub fn new(url: &str) -> Result { Ok(Self { base_url: url.to_owned(), }) } - pub fn client(&self, addons: &str) -> io::Result { + pub fn client(&self, addons: &str) -> Result { let mut easy = Easy::new(); easy.url(&format!("{}/{addons}", self.base_url))?; Ok(easy) } - pub fn raw_post(&self, addons: &str, body: &[u8]) -> io::Result> { + pub fn raw_post(&self, addons: &str, body: &[u8]) -> Result> { let mut easy = self.client(addons)?; easy.post(true)?; easy.post_fields_copy(body)?; @@ -42,7 +43,7 @@ impl EsploraAPI { Ok(body) } - pub fn raw_call(&self, addons: &str) -> io::Result> { + pub fn raw_call(&self, addons: &str) -> Result> { let mut easy = self.client(addons)?; let mut body = Vec::new(); { @@ -58,21 +59,23 @@ impl EsploraAPI { } // perform a generic call - pub fn call(&self, addons: &str) -> io::Result { + pub fn call(&self, addons: &str) -> Result { let body = self.raw_call(addons)?; - let parsed_json: D = json::from_slice(&body)?; + let parsed_json: D = json::from_slice(&body).map_err(|e| { + let mut err = Error::new(400); + err.set_extra(format!("{e}")); + err + })?; Ok(parsed_json) } } #[cfg(test)] mod tests { - use std::io; - use super::*; #[test] - fn test_tip() -> io::Result<()> { + fn test_tip() -> Result<()> { let api = EsploraAPI::new("https://blockstream.info/api")?; let hash = api.raw_call("blocks/tip/hash")?; let hash = String::from_utf8(hash).unwrap();