Browse Source

Make it possible to only parse exchange rates, without fetching

David Peter 2 years ago
parent
commit
a9964a1893
2 changed files with 22 additions and 9 deletions
  1. 4 1
      numbat-exchange-rates/Cargo.toml
  2. 18 8
      numbat-exchange-rates/src/lib.rs

+ 4 - 1
numbat-exchange-rates/Cargo.toml

@@ -10,5 +10,8 @@ license = "MIT OR Apache-2.0"
 rust-version = "1.70"
 
 [dependencies]
-attohttpc = { version = "0.26.0", default-features = false, features = ["tls-rustls-webpki-roots"] }
+attohttpc = { version = "0.26.0", default-features = false, features = ["tls-rustls-webpki-roots"], optional = true }
 quick-xml = "0.30.0"
+
+[features]
+default = ["attohttpc"]

+ 18 - 8
numbat-exchange-rates/src/lib.rs

@@ -5,16 +5,10 @@ use quick_xml::reader::Reader;
 
 pub type ExchangeRates = HashMap<String, f64>;
 
-pub fn fetch_exchange_rates() -> Option<ExchangeRates> {
+pub fn parse_exchange_rates(xml_content: &str) -> Option<ExchangeRates> {
     let mut rates = ExchangeRates::default();
 
-    let xml = attohttpc::get("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")
-        .send()
-        .ok()?
-        .text()
-        .ok()?;
-
-    let mut reader = Reader::from_str(&xml);
+    let mut reader = Reader::from_str(&xml_content);
     loop {
         match reader.read_event().ok()? {
             Event::Eof => break,
@@ -39,6 +33,22 @@ pub fn fetch_exchange_rates() -> Option<ExchangeRates> {
     Some(rates)
 }
 
+const ECB_XML_URL: &str = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
+
+#[cfg(not(feature = "wasm"))]
+fn fetch_ecb_xml() -> Option<String> {
+    attohttpc::get(ECB_XML_URL)
+        .send()
+        .ok()?
+        .text()
+        .ok()
+}
+
+pub fn fetch_exchange_rates() -> Option<ExchangeRates> {
+    let xml_content = fetch_ecb_xml()?;
+    parse_exchange_rates(&xml_content)
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;