Skip to content

Commit

Permalink
Better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
LostQuasar committed Oct 13, 2024
1 parent 57c7ab2 commit e7e35c9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
25 changes: 14 additions & 11 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@ impl OpenShockAPI {
}

/// Create a new instance of the api interface with a default key and the base_url, because OpenShock can be self hosted `base_url` can be any url without the leading `/` if `None` is provided the default of <https://api.shocklink.net> is used.
pub fn new(base_url: Option<String>, default_key: String) -> Self {
pub fn new(base_url: Option<String>, default_key: String) -> Result<Self, Error> {
let mut builder = Self::builder().with_default_api_token(default_key);
if let Some(base_url) = base_url {
builder = builder.with_base_url(base_url);
}
builder.build().unwrap()
builder.build()
}

/// Gets user info from the provided API key, the default key from the instance is used if `None` is provided
pub async fn get_user_info(&self, api_key: Option<String>) -> Result<SelfResponse, Error> {
pub async fn get_user_info(&self, api_key: Option<String>) -> Result<Option<SelfResponse>, Error> {
let resp = self
.client
.get(format!("{}/1/users/self", self.base_url))
Expand All @@ -45,18 +45,19 @@ impl OpenShockAPI {
api_key.unwrap_or(self.default_key.clone()),
)
.send()
.await?;
.await?
.error_for_status()?;
let self_base_response: BaseResponse<SelfResponse> =
serde_json::from_str(resp.text().await?.as_str())?;
Ok(self_base_response.data.unwrap())
Ok(self_base_response.data)
}

/// Gets a list of shockers that the user has access to from either their own shockers or ones shared with them
pub async fn get_shockers(
&self,
source: ListShockerSource,
api_key: Option<String>,
) -> Result<Vec<ListShockersResponse>, Error> {
) -> Result<Option<Vec<ListShockersResponse>>, Error> {
let resp = self
.client
.get(format!("{}/1/shockers/{:?}", self.base_url, source))
Expand All @@ -65,10 +66,11 @@ impl OpenShockAPI {
api_key.unwrap_or(self.default_key.clone()),
)
.send()
.await?;
.await?
.error_for_status()?;
let list_shockers_response: BaseResponse<Vec<ListShockersResponse>> =
serde_json::from_str(resp.text().await?.as_str())?;
Ok(list_shockers_response.data.unwrap())
Ok(list_shockers_response.data)
}

///Sends a control request to the api and returns the response message which should be "Successfully sent control messages" exactly if it was successful
Expand All @@ -79,7 +81,7 @@ impl OpenShockAPI {
intensity: u8,
duration: u16,
api_key: Option<String>,
) -> Result<String, Error> {
) -> Result<Option<String>, Error> {
match intensity {
1..=100 => {}
_ => {
Expand Down Expand Up @@ -114,9 +116,10 @@ impl OpenShockAPI {
api_key.unwrap_or(self.default_key.clone()),
)
.send()
.await?;
.await?
.error_for_status()?;
let base_response: BaseResponse<String> =
serde_json::from_str(resp.text().await?.as_str())?;
Ok(base_response.message.unwrap())
Ok(base_response.message)
}
}
10 changes: 5 additions & 5 deletions tests/tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use dotenv::dotenv;
use rzap::{api::{ListShockerSource, OpenShockAPI},api_builder::OpenShockAPIBuilder, data_type::ControlType};
use rzap::{api::{ListShockerSource, OpenShockAPI},api_builder::OpenShockAPIBuilder, data_type::{ControlType, SelfResponse}, error::Error};
use std::hash::{DefaultHasher, Hash, Hasher};


Expand Down Expand Up @@ -32,7 +32,7 @@ async fn get_shockers_test() {

let result = openshock_api.get_shockers(ListShockerSource::Own, None).await;
assert_eq!(
calculate_hash(&result.unwrap()[0].shockers[0].id),
calculate_hash(&result.unwrap().unwrap()[0].shockers[0].id),
calculate_hash(&shocker_test_id)
);
}
Expand All @@ -46,7 +46,7 @@ async fn post_control_test() {
let result = openshock_api
.post_control(shocker_test_id, ControlType::Sound, 1, 300, None)
.await;
assert_eq!(&result.unwrap(), &"Successfully sent control messages");
assert_eq!(&result.unwrap().unwrap(), &"Successfully sent control messages");
}

#[tokio::test]
Expand All @@ -55,9 +55,9 @@ async fn get_user_info_test() {
let user_test_id = dotenv::var("USER_TEST_ID").expect("missing USER_TEST_ID");
assert_ne!(user_test_id, "");

let result: Result<rzap::data_type::SelfResponse, rzap::error::Error> = openshock_api.get_user_info(None).await;
let result: Result<Option<SelfResponse>, Error> = openshock_api.get_user_info(None).await;
assert_eq!(
calculate_hash(&result.unwrap().id),
calculate_hash(&result.unwrap().unwrap().id),
calculate_hash(&user_test_id)
);
}

0 comments on commit e7e35c9

Please sign in to comment.