From a6afa81d1d9f2dd7d10fe7c0555ae8a8a6d84867 Mon Sep 17 00:00:00 2001 From: Daniel Schadt Date: Thu, 12 Dec 2019 01:25:28 +0100 Subject: use helper traits for better code --- src/api/mod.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'src/api') diff --git a/src/api/mod.rs b/src/api/mod.rs index 9c771fd..c33e6ba 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -16,7 +16,7 @@ pub use self::{ use image::DynamicImage; use itertools::Itertools; -use reqwest::{Client, Url}; +use reqwest::{Client, StatusCode, Url}; use serde::{de::DeserializeOwned, Serialize}; use std::path::Path; @@ -28,6 +28,7 @@ const BASE_URL: &str = "https://api.guildwars2.com/v2/"; quick_error! { #[derive(Debug)] pub enum ApiError { + ItemNotFound {} SerializationError(err: serde_json::Error) { cause(err) from() @@ -47,6 +48,23 @@ quick_error! { } } +trait ApiResponse +where + Self: Sized, +{ + fn ensure_found(self) -> Result; +} + +impl ApiResponse for reqwest::Response { + fn ensure_found(self) -> Result { + if self.status() == StatusCode::PARTIAL_CONTENT || self.status() == StatusCode::NOT_FOUND { + Err(ApiError::ItemNotFound) + } else { + Ok(self) + } + } +} + /// Trait for API objects that have an ID. /// /// This is used by [`Api`](struct.Api.html) to properly retrieve and cache objects. @@ -143,6 +161,7 @@ impl Api { .get(url) .query(&[("ids", api_arg)]) .send()? + .ensure_found()? .json()?; for result in &resp { let cache_path = format!("{}{}", cache_prefix, result.get_id().to_string()); -- cgit v1.2.3