From 6c1a836ec0a347a50cb4f71ff178d792ecb88b2b Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Sat, 23 Feb 2019 22:55:36 +0100 Subject: Propagate errors from the server back up through the Api. Also create a small helper method to fetch the payload from the server, to avoid too much repitition. --- src/api.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/api.rs b/src/api.rs index 6c85d76..b0b89cf 100644 --- a/src/api.rs +++ b/src/api.rs @@ -63,21 +63,25 @@ impl Api { /// Fetch the list of stations and their basic data from the api. pub fn stations(&self) -> ApiResult> { - let response_json = self.client.get(&url_for("stations")) - .send()? - .text()?; - + let response_json = self.get("stations")?; let v: StationContainer = serde_json::from_str(&response_json)?; Ok(v.stations) } /// Fetch availability status for all stations pub fn station_availability(&self) -> ApiResult> { - let response_json = self.client.get(&url_for("stations/availability")) - .send()? - .text()?; - + let response_json = self.get("stations/availability")?; let v: StationAvailabilityContainer = serde_json::from_str(&response_json)?; Ok(v.stations) } + + /// A helper method to fetch payloads from the upstream API + fn get(&self, path: &str) -> ApiResult { + self.client + .get(&url_for(path)) + .send()? + .error_for_status()? + .text() + .map_err(crate::error::Error::ReqwestError) + } } -- cgit v1.2.3