Change InstanceServerError to ChorusLibError

The name InstanceServerError was chosen without thinking about it too much, very early in development. The new name suits this custom Error type way better, in my opinion.
This commit is contained in:
bitfl0wer 2023-06-08 22:16:23 +02:00
parent 66ca26db0f
commit b0a19faa48
13 changed files with 105 additions and 94 deletions

View File

@ -6,7 +6,7 @@ pub mod login {
use serde_json::{from_str, json}; use serde_json::{from_str, json};
use crate::api::limits::LimitType; use crate::api::limits::LimitType;
use crate::errors::InstanceServerError; use crate::errors::ChorusLibError;
use crate::instance::{Instance, UserMeta}; use crate::instance::{Instance, UserMeta};
use crate::limit::LimitedRequester; use crate::limit::LimitedRequester;
use crate::types::{ErrorResponse, LoginResult, LoginSchema}; use crate::types::{ErrorResponse, LoginResult, LoginSchema};
@ -15,7 +15,7 @@ pub mod login {
pub async fn login_account( pub async fn login_account(
&mut self, &mut self,
login_schema: &LoginSchema, login_schema: &LoginSchema,
) -> Result<UserMeta, InstanceServerError> { ) -> Result<UserMeta, ChorusLibError> {
let mut requester = LimitedRequester::new().await; let mut requester = LimitedRequester::new().await;
let json_schema = json!(login_schema); let json_schema = json!(login_schema);
let client = Client::new(); let client = Client::new();
@ -34,7 +34,7 @@ pub mod login {
) )
.await; .await;
if response.is_err() { if response.is_err() {
return Err(InstanceServerError::NoResponse); return Err(ChorusLibError::NoResponse);
} }
let response_unwrap = response.unwrap(); let response_unwrap = response.unwrap();
@ -49,7 +49,7 @@ pub mod login {
error += &(error_item.message.to_string() + " (" + &error_item.code + ")"); error += &(error_item.message.to_string() + " (" + &error_item.code + ")");
} }
} }
return Err(InstanceServerError::InvalidFormBodyError { error_type, error }); return Err(ChorusLibError::InvalidFormBodyError { error_type, error });
} }
let cloned_limits = self.limits.clone(); let cloned_limits = self.limits.clone();

View File

@ -6,7 +6,7 @@ pub mod register {
use crate::{ use crate::{
api::limits::LimitType, api::limits::LimitType,
errors::InstanceServerError, errors::ChorusLibError,
instance::{Instance, Token, UserMeta}, instance::{Instance, Token, UserMeta},
limit::LimitedRequester, limit::LimitedRequester,
types::{ErrorResponse, RegisterSchema}, types::{ErrorResponse, RegisterSchema},
@ -18,12 +18,12 @@ pub mod register {
# Arguments # Arguments
* `register_schema` - The [`RegisterSchema`] that contains all the information that is needed to register a new user. * `register_schema` - The [`RegisterSchema`] that contains all the information that is needed to register a new user.
# Errors # Errors
* [`InstanceServerError`] - If the server does not respond. * [`ChorusLibError`] - If the server does not respond.
*/ */
pub async fn register_account( pub async fn register_account(
&mut self, &mut self,
register_schema: &RegisterSchema, register_schema: &RegisterSchema,
) -> Result<UserMeta, InstanceServerError> { ) -> Result<UserMeta, ChorusLibError> {
let json_schema = json!(register_schema); let json_schema = json!(register_schema);
let mut limited_requester = LimitedRequester::new().await; let mut limited_requester = LimitedRequester::new().await;
let client = Client::new(); let client = Client::new();
@ -42,7 +42,7 @@ pub mod register {
) )
.await; .await;
if response.is_err() { if response.is_err() {
return Err(InstanceServerError::NoResponse); return Err(ChorusLibError::NoResponse);
} }
let response_unwrap = response.unwrap(); let response_unwrap = response.unwrap();
@ -59,7 +59,7 @@ pub mod register {
error += &(error_item.message.to_string() + " (" + &error_item.code + ")"); error += &(error_item.message.to_string() + " (" + &error_item.code + ")");
} }
} }
return Err(InstanceServerError::InvalidFormBodyError { error_type, error }); return Err(ChorusLibError::InvalidFormBodyError { error_type, error });
} }
let user_object = self.get_user(token.clone(), None).await.unwrap(); let user_object = self.get_user(token.clone(), None).await.unwrap();
let settings = let settings =

View File

@ -2,17 +2,14 @@ use reqwest::Client;
use serde_json::{from_str, to_string}; use serde_json::{from_str, to_string};
use crate::{ use crate::{
errors::InstanceServerError, errors::ChorusLibError,
instance::UserMeta, instance::UserMeta,
limit::LimitedRequester, limit::LimitedRequester,
types::{Channel, ChannelModifySchema}, types::{Channel, ChannelModifySchema},
}; };
impl Channel { impl Channel {
pub async fn get( pub async fn get(user: &mut UserMeta, channel_id: &str) -> Result<Channel, ChorusLibError> {
user: &mut UserMeta,
channel_id: &str,
) -> Result<Channel, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let request = Client::new() let request = Client::new()
.get(format!( .get(format!(
@ -37,7 +34,7 @@ impl Channel {
let result_text = result.text().await.unwrap(); let result_text = result.text().await.unwrap();
match from_str::<Channel>(&result_text) { match from_str::<Channel>(&result_text) {
Ok(object) => Ok(object), Ok(object) => Ok(object),
Err(e) => Err(InstanceServerError::RequestErrorError { Err(e) => Err(ChorusLibError::RequestErrorError {
url: format!("{}/channels/{}/", belongs_to.urls.get_api(), channel_id), url: format!("{}/channels/{}/", belongs_to.urls.get_api(), channel_id),
error: e.to_string(), error: e.to_string(),
}), }),
@ -56,8 +53,8 @@ impl Channel {
/// ///
/// # Returns /// # Returns
/// ///
/// An `Option` that contains an `InstanceServerError` if an error occurred during the request, or `None` if the request was successful. /// An `Option` that contains an `ChorusLibError` if an error occurred during the request, or `None` if the request was successful.
pub async fn delete(self, user: &mut UserMeta) -> Option<InstanceServerError> { pub async fn delete(self, user: &mut UserMeta) -> Option<ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let request = Client::new() let request = Client::new()
.delete(format!( .delete(format!(
@ -94,12 +91,12 @@ impl Channel {
/// ///
/// # Returns /// # Returns
/// ///
/// A `Result` that contains a `Channel` object if the request was successful, or an `InstanceServerError` if an error occurred during the request. /// A `Result` that contains a `Channel` object if the request was successful, or an `ChorusLibError` if an error occurred during the request.
pub async fn modify( pub async fn modify(
modify_data: ChannelModifySchema, modify_data: ChannelModifySchema,
channel_id: &str, channel_id: &str,
user: &mut UserMeta, user: &mut UserMeta,
) -> Result<Channel, InstanceServerError> { ) -> Result<Channel, ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let request = Client::new() let request = Client::new()
.patch(format!( .patch(format!(

View File

@ -17,14 +17,14 @@ impl Message {
* `limits_instance` - The [`Limits`] of the instance. * `limits_instance` - The [`Limits`] of the instance.
* `requester` - The [`LimitedRequester`] that will be used to make requests to the Spacebar server. * `requester` - The [`LimitedRequester`] that will be used to make requests to the Spacebar server.
# Errors # Errors
* [`InstanceServerError`] - If the message cannot be sent. * [`ChorusLibError`] - If the message cannot be sent.
*/ */
pub async fn send( pub async fn send(
user: &mut UserMeta, user: &mut UserMeta,
channel_id: String, channel_id: String,
message: &mut MessageSendSchema, message: &mut MessageSendSchema,
files: Option<Vec<PartialDiscordFileAttachment>>, files: Option<Vec<PartialDiscordFileAttachment>>,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> { ) -> Result<reqwest::Response, crate::errors::ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let url_api = belongs_to.urls.get_api(); let url_api = belongs_to.urls.get_api();
let mut requester = LimitedRequester::new().await; let mut requester = LimitedRequester::new().await;
@ -98,14 +98,14 @@ impl UserMeta {
* `limits_instance` - The [`Limits`] of the instance. * `limits_instance` - The [`Limits`] of the instance.
* `requester` - The [`LimitedRequester`] that will be used to make requests to the Spacebar server. * `requester` - The [`LimitedRequester`] that will be used to make requests to the Spacebar server.
# Errors # Errors
* [`InstanceServerError`] - If the message cannot be sent. * [`ChorusLibError`] - If the message cannot be sent.
*/ */
pub async fn send_message( pub async fn send_message(
&mut self, &mut self,
message: &mut MessageSendSchema, message: &mut MessageSendSchema,
channel_id: String, channel_id: String,
files: Option<Vec<PartialDiscordFileAttachment>>, files: Option<Vec<PartialDiscordFileAttachment>>,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> { ) -> Result<reqwest::Response, crate::errors::ChorusLibError> {
Message::send(self, channel_id, message, files).await Message::send(self, channel_id, message, files).await
} }
} }

View File

@ -23,7 +23,7 @@ impl ReactionMeta {
* `user` - A mutable reference to a [`UserMeta`] instance. * `user` - A mutable reference to a [`UserMeta`] instance.
# Returns # Returns
A `Result` containing a [`reqwest::Response`] or a [`crate::errors::InstanceServerError`]. A `Result` containing a [`reqwest::Response`] or a [`crate::errors::ChorusLibError`].
Fires a `Message Reaction Remove All` Gateway event. Fires a `Message Reaction Remove All` Gateway event.
# Reference # Reference
@ -32,7 +32,7 @@ impl ReactionMeta {
pub async fn delete_all( pub async fn delete_all(
&self, &self,
user: &mut UserMeta, user: &mut UserMeta,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> { ) -> Result<reqwest::Response, crate::errors::ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!( let url = format!(
"{}/channels/{}/messages/{}/reactions/", "{}/channels/{}/messages/{}/reactions/",
@ -62,7 +62,7 @@ impl ReactionMeta {
* `user` - A mutable reference to a [`UserMeta`] instance. * `user` - A mutable reference to a [`UserMeta`] instance.
# Returns # Returns
A `Result` containing a [`reqwest::Response`] or a [`crate::errors::InstanceServerError`]. A `Result` containing a [`reqwest::Response`] or a [`crate::errors::ChorusLibError`].
# Reference # Reference
See [https://discord.com/developers/docs/resources/channel#get-reactions](https://discord.com/developers/docs/resources/channel#get-reactions) See [https://discord.com/developers/docs/resources/channel#get-reactions](https://discord.com/developers/docs/resources/channel#get-reactions)
@ -71,7 +71,7 @@ impl ReactionMeta {
&self, &self,
emoji: &str, emoji: &str,
user: &mut UserMeta, user: &mut UserMeta,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> { ) -> Result<reqwest::Response, crate::errors::ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!( let url = format!(
"{}/channels/{}/messages/{}/reactions/{}/", "{}/channels/{}/messages/{}/reactions/{}/",
@ -103,7 +103,7 @@ impl ReactionMeta {
* `user` - A mutable reference to a [`UserMeta`] instance. * `user` - A mutable reference to a [`UserMeta`] instance.
# Returns # Returns
A `Result` containing a [`reqwest::Response`] or a [`crate::errors::InstanceServerError`]. A `Result` containing a [`reqwest::Response`] or a [`crate::errors::ChorusLibError`].
Fires a `Message Reaction Remove Emoji` Gateway event. Fires a `Message Reaction Remove Emoji` Gateway event.
# Reference # Reference
@ -113,7 +113,7 @@ impl ReactionMeta {
&self, &self,
emoji: &str, emoji: &str,
user: &mut UserMeta, user: &mut UserMeta,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> { ) -> Result<reqwest::Response, crate::errors::ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!( let url = format!(
"{}/channels/{}/messages/{}/reactions/{}/", "{}/channels/{}/messages/{}/reactions/{}/",
@ -148,7 +148,7 @@ impl ReactionMeta {
* `user` - A mutable reference to a [`UserMeta`] instance. * `user` - A mutable reference to a [`UserMeta`] instance.
# Returns # Returns
A `Result` containing a [`reqwest::Response`] or a [`crate::errors::InstanceServerError`]. A `Result` containing a [`reqwest::Response`] or a [`crate::errors::ChorusLibError`].
Returns a 204 empty response on success. Returns a 204 empty response on success.
Fires a Message Reaction Add Gateway event. Fires a Message Reaction Add Gateway event.
@ -159,7 +159,7 @@ impl ReactionMeta {
&self, &self,
emoji: &str, emoji: &str,
user: &mut UserMeta, user: &mut UserMeta,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> { ) -> Result<reqwest::Response, crate::errors::ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!( let url = format!(
"{}/channels/{}/messages/{}/reactions/{}/@me/", "{}/channels/{}/messages/{}/reactions/{}/@me/",
@ -190,7 +190,7 @@ impl ReactionMeta {
* `user` - A mutable reference to a [`UserMeta`] instance. * `user` - A mutable reference to a [`UserMeta`] instance.
# Returns # Returns
A `Result` containing a [`reqwest::Response`] or a [`crate::errors::InstanceServerError`]. A `Result` containing a [`reqwest::Response`] or a [`crate::errors::ChorusLibError`].
Returns a 204 empty response on success. Returns a 204 empty response on success.
Fires a `Message Reaction Remove` Gateway event. Fires a `Message Reaction Remove` Gateway event.
@ -201,7 +201,7 @@ impl ReactionMeta {
&self, &self,
emoji: &str, emoji: &str,
user: &mut UserMeta, user: &mut UserMeta,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> { ) -> Result<reqwest::Response, crate::errors::ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!( let url = format!(
"{}/channels/{}/messages/{}/reactions/{}/@me/", "{}/channels/{}/messages/{}/reactions/{}/@me/",
@ -235,7 +235,7 @@ impl ReactionMeta {
* `user` - A mutable reference to a [`UserMeta`] instance. * `user` - A mutable reference to a [`UserMeta`] instance.
# Returns # Returns
A `Result` containing a [`reqwest::Response`] or a [`crate::errors::InstanceServerError`]. A `Result` containing a [`reqwest::Response`] or a [`crate::errors::ChorusLibError`].
Returns a 204 empty response on success. Returns a 204 empty response on success.
Fires a Message Reaction Remove Gateway event. Fires a Message Reaction Remove Gateway event.
@ -247,7 +247,7 @@ impl ReactionMeta {
user_id: &str, user_id: &str,
emoji: &str, emoji: &str,
user: &mut UserMeta, user: &mut UserMeta,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> { ) -> Result<reqwest::Response, crate::errors::ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!( let url = format!(
"{}/channels/{}/messages/{}/reactions/{}/{}", "{}/channels/{}/messages/{}/reactions/{}/{}",

View File

@ -3,7 +3,7 @@ use serde_json::from_str;
use serde_json::to_string; use serde_json::to_string;
use crate::api::limits::Limits; use crate::api::limits::Limits;
use crate::errors::InstanceServerError; use crate::errors::ChorusLibError;
use crate::instance::UserMeta; use crate::instance::UserMeta;
use crate::limit::LimitedRequester; use crate::limit::LimitedRequester;
use crate::types::{Channel, ChannelCreateSchema, Guild, GuildCreateResponse, GuildCreateSchema}; use crate::types::{Channel, ChannelCreateSchema, Guild, GuildCreateResponse, GuildCreateSchema};
@ -23,12 +23,12 @@ impl Guild {
/// ///
/// # Errors /// # Errors
/// ///
/// Returns an `InstanceServerError` if the request fails. /// Returns an `ChorusLibError` if the request fails.
/// ///
pub async fn create( pub async fn create(
user: &mut UserMeta, user: &mut UserMeta,
guild_create_schema: GuildCreateSchema, guild_create_schema: GuildCreateSchema,
) -> Result<Guild, crate::errors::InstanceServerError> { ) -> Result<Guild, crate::errors::ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!("{}/guilds/", belongs_to.urls.get_api()); let url = format!("{}/guilds/", belongs_to.urls.get_api());
let request = reqwest::Client::new() let request = reqwest::Client::new()
@ -71,7 +71,7 @@ impl Guild {
/// ///
/// # Returns /// # Returns
/// ///
/// An `Option` containing an `InstanceServerError` if an error occurred during the request, otherwise `None`. /// An `Option` containing an `ChorusLibError` if an error occurred during the request, otherwise `None`.
/// ///
/// # Example /// # Example
/// ///
@ -85,7 +85,7 @@ impl Guild {
/// None => println!("Guild deleted successfully"), /// None => println!("Guild deleted successfully"),
/// } /// }
/// ``` /// ```
pub async fn delete(user: &mut UserMeta, guild_id: &str) -> Option<InstanceServerError> { pub async fn delete(user: &mut UserMeta, guild_id: &str) -> Option<ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!("{}/guilds/{}/delete/", belongs_to.urls.get_api(), guild_id); let url = format!("{}/guilds/{}/delete/", belongs_to.urls.get_api(), guild_id);
let request = reqwest::Client::new() let request = reqwest::Client::new()
@ -119,12 +119,12 @@ impl Guild {
/// ///
/// # Returns /// # Returns
/// ///
/// A `Result` containing a `reqwest::Response` if the request was successful, or an `InstanceServerError` if there was an error. /// A `Result` containing a `reqwest::Response` if the request was successful, or an `ChorusLibError` if there was an error.
pub async fn create_channel( pub async fn create_channel(
&self, &self,
user: &mut UserMeta, user: &mut UserMeta,
schema: ChannelCreateSchema, schema: ChannelCreateSchema,
) -> Result<Channel, InstanceServerError> { ) -> Result<Channel, ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
Channel::_create( Channel::_create(
&user.token, &user.token,
@ -137,7 +137,7 @@ impl Guild {
.await .await
} }
/// Returns a `Result` containing a vector of `Channel` structs if the request was successful, or an `InstanceServerError` if there was an error. /// Returns a `Result` containing a vector of `Channel` structs if the request was successful, or an `ChorusLibError` if there was an error.
/// ///
/// # Arguments /// # Arguments
/// ///
@ -146,7 +146,7 @@ impl Guild {
/// * `limits_user` - A mutable reference to a `Limits` struct containing the user's rate limits. /// * `limits_user` - A mutable reference to a `Limits` struct containing the user's rate limits.
/// * `limits_instance` - A mutable reference to a `Limits` struct containing the instance's rate limits. /// * `limits_instance` - A mutable reference to a `Limits` struct containing the instance's rate limits.
/// ///
pub async fn channels(&self, user: &mut UserMeta) -> Result<Vec<Channel>, InstanceServerError> { pub async fn channels(&self, user: &mut UserMeta) -> Result<Vec<Channel>, ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let request = Client::new() let request = Client::new()
.get(format!( .get(format!(
@ -171,7 +171,7 @@ impl Guild {
let stringed_response = match result.text().await { let stringed_response = match result.text().await {
Ok(value) => value, Ok(value) => value,
Err(e) => { Err(e) => {
return Err(InstanceServerError::InvalidResponseError { return Err(ChorusLibError::InvalidResponseError {
error: e.to_string(), error: e.to_string(),
}) })
} }
@ -179,14 +179,14 @@ impl Guild {
let _: Vec<Channel> = match from_str(&stringed_response) { let _: Vec<Channel> = match from_str(&stringed_response) {
Ok(result) => return Ok(result), Ok(result) => return Ok(result),
Err(e) => { Err(e) => {
return Err(InstanceServerError::InvalidResponseError { return Err(ChorusLibError::InvalidResponseError {
error: e.to_string(), error: e.to_string(),
}) })
} }
}; };
} }
/// Returns a `Result` containing a `Guild` struct if the request was successful, or an `InstanceServerError` if there was an error. /// Returns a `Result` containing a `Guild` struct if the request was successful, or an `ChorusLibError` if there was an error.
/// ///
/// # Arguments /// # Arguments
/// ///
@ -196,7 +196,7 @@ impl Guild {
/// * `limits_user` - A mutable reference to a `Limits` struct containing the user's rate limits. /// * `limits_user` - A mutable reference to a `Limits` struct containing the user's rate limits.
/// * `limits_instance` - A mutable reference to a `Limits` struct containing the instance's rate limits. /// * `limits_instance` - A mutable reference to a `Limits` struct containing the instance's rate limits.
/// ///
pub async fn get(user: &mut UserMeta, guild_id: &str) -> Result<Guild, InstanceServerError> { pub async fn get(user: &mut UserMeta, guild_id: &str) -> Result<Guild, ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
Guild::_get( Guild::_get(
&format!("{}", belongs_to.urls.get_api()), &format!("{}", belongs_to.urls.get_api()),
@ -216,7 +216,7 @@ impl Guild {
token: &str, token: &str,
limits_user: &mut Limits, limits_user: &mut Limits,
limits_instance: &mut Limits, limits_instance: &mut Limits,
) -> Result<Guild, InstanceServerError> { ) -> Result<Guild, ChorusLibError> {
let request = Client::new() let request = Client::new()
.get(format!("{}/guilds/{}/", url_api, guild_id)) .get(format!("{}/guilds/{}/", url_api, guild_id))
.bearer_auth(token); .bearer_auth(token);
@ -252,12 +252,12 @@ impl Channel {
/// ///
/// # Returns /// # Returns
/// ///
/// A `Result` containing a `reqwest::Response` if the request was successful, or an `InstanceServerError` if there was an error. /// A `Result` containing a `reqwest::Response` if the request was successful, or an `ChorusLibError` if there was an error.
pub async fn create( pub async fn create(
user: &mut UserMeta, user: &mut UserMeta,
guild_id: &str, guild_id: &str,
schema: ChannelCreateSchema, schema: ChannelCreateSchema,
) -> Result<Channel, InstanceServerError> { ) -> Result<Channel, ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
Channel::_create( Channel::_create(
&user.token, &user.token,
@ -277,7 +277,7 @@ impl Channel {
schema: ChannelCreateSchema, schema: ChannelCreateSchema,
limits_user: &mut Limits, limits_user: &mut Limits,
limits_instance: &mut Limits, limits_instance: &mut Limits,
) -> Result<Channel, InstanceServerError> { ) -> Result<Channel, ChorusLibError> {
let request = Client::new() let request = Client::new()
.post(format!("{}/guilds/{}/channels/", url_api, guild_id)) .post(format!("{}/guilds/{}/channels/", url_api, guild_id))
.bearer_auth(token) .bearer_auth(token)
@ -297,7 +297,7 @@ impl Channel {
}; };
match from_str::<Channel>(&result.text().await.unwrap()) { match from_str::<Channel>(&result.text().await.unwrap()) {
Ok(object) => Ok(object), Ok(object) => Ok(object),
Err(e) => Err(InstanceServerError::RequestErrorError { Err(e) => Err(ChorusLibError::RequestErrorError {
url: format!("{}/guilds/{}/channels/", url_api, guild_id), url: format!("{}/guilds/{}/channels/", url_api, guild_id),
error: e.to_string(), error: e.to_string(),
}), }),

View File

@ -1,17 +1,17 @@
use reqwest::Client; use reqwest::Client;
use serde_json::from_str; use serde_json::{from_str, to_string};
use crate::{ use crate::{
instance::UserMeta, instance::UserMeta,
limit::LimitedRequester, limit::LimitedRequester,
types::{self, RoleObject}, types::{self, RoleCreateModifySchema, RoleObject},
}; };
impl types::RoleObject { impl types::RoleObject {
pub async fn get_all( pub async fn get_all(
user: &mut UserMeta, user: &mut UserMeta,
guild_id: &str, guild_id: &str,
) -> Result<Option<Vec<RoleObject>>, crate::errors::InstanceServerError> { ) -> Result<Option<Vec<RoleObject>>, crate::errors::ChorusLibError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!("{}/guilds/{}/roles/", belongs_to.urls.get_api(), guild_id); let url = format!("{}/guilds/{}/roles/", belongs_to.urls.get_api(), guild_id);
let request = Client::new().get(url).bearer_auth(user.token()); let request = Client::new().get(url).bearer_auth(user.token());
@ -36,4 +36,18 @@ impl types::RoleObject {
Ok(Some(roles)) Ok(Some(roles))
} }
pub async fn create(
user: &mut UserMeta,
guild_id: &str,
role_create_schema: RoleCreateModifySchema,
) {
let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!("{}/guilds/{}/roles/", belongs_to.urls.get_api(), guild_id);
let body = match to_string::<RoleCreateModifySchema>(&role_create_schema) {
Ok(string) => string,
Err(e) =>
};
let request = Client::new().post(url).bearer_auth(user.token()).body()
}
} }

View File

@ -1,7 +1,7 @@
use reqwest::Client; use reqwest::Client;
use serde_json::from_str; use serde_json::from_str;
use crate::errors::InstanceServerError; use crate::errors::ChorusLibError;
use crate::instance::Instance; use crate::instance::Instance;
use crate::types::GeneralConfiguration; use crate::types::GeneralConfiguration;
@ -9,17 +9,17 @@ impl Instance {
/** /**
Gets the instance policies schema. Gets the instance policies schema.
# Errors # Errors
[`InstanceServerError`] - If the request fails. [`ChorusLibError`] - If the request fails.
*/ */
pub async fn general_configuration_schema( pub async fn general_configuration_schema(
&self, &self,
) -> Result<GeneralConfiguration, InstanceServerError> { ) -> Result<GeneralConfiguration, ChorusLibError> {
let client = Client::new(); let client = Client::new();
let endpoint_url = self.urls.get_api().to_string() + "/policies/instance/"; let endpoint_url = self.urls.get_api().to_string() + "/policies/instance/";
let request = match client.get(&endpoint_url).send().await { let request = match client.get(&endpoint_url).send().await {
Ok(result) => result, Ok(result) => result,
Err(e) => { Err(e) => {
return Err(InstanceServerError::RequestErrorError { return Err(ChorusLibError::RequestErrorError {
url: endpoint_url, url: endpoint_url,
error: e.to_string(), error: e.to_string(),
}); });
@ -27,7 +27,7 @@ impl Instance {
}; };
if !request.status().as_str().starts_with('2') { if !request.status().as_str().starts_with('2') {
return Err(InstanceServerError::ReceivedErrorCodeError { return Err(ChorusLibError::ReceivedErrorCodeError {
error_code: request.status().to_string(), error_code: request.status().to_string(),
}); });
} }

View File

@ -3,7 +3,7 @@ use serde_json::{from_str, to_string};
use crate::{ use crate::{
api::limits::Limits, api::limits::Limits,
errors::InstanceServerError, errors::ChorusLibError,
instance::{Instance, UserMeta}, instance::{Instance, UserMeta},
limit::LimitedRequester, limit::LimitedRequester,
types::{User, UserModifySchema, UserSettings}, types::{User, UserModifySchema, UserSettings},
@ -18,12 +18,9 @@ impl UserMeta {
* `id` - The id of the user that will be retrieved. If this is None, the current user will be retrieved. * `id` - The id of the user that will be retrieved. If this is None, the current user will be retrieved.
* `instance_limits` - The [`Limits`] of the instance. * `instance_limits` - The [`Limits`] of the instance.
# Errors # Errors
* [`InstanceServerError`] - If the request fails. * [`ChorusLibError`] - If the request fails.
*/ */
pub async fn get( pub async fn get(user: &mut UserMeta, id: Option<&String>) -> Result<User, ChorusLibError> {
user: &mut UserMeta,
id: Option<&String>,
) -> Result<User, InstanceServerError> {
User::get(user, id).await User::get(user, id).await
} }
@ -31,7 +28,7 @@ impl UserMeta {
token: &String, token: &String,
url_api: &String, url_api: &String,
instance_limits: &mut Limits, instance_limits: &mut Limits,
) -> Result<UserSettings, InstanceServerError> { ) -> Result<UserSettings, ChorusLibError> {
User::get_settings(token, url_api, instance_limits).await User::get_settings(token, url_api, instance_limits).await
} }
@ -43,16 +40,16 @@ impl UserMeta {
/// ///
/// # Errors /// # Errors
/// ///
/// Returns an `InstanceServerError` if the request fails or if a password is required but not provided. /// Returns an `ChorusLibError` if the request fails or if a password is required but not provided.
pub async fn modify( pub async fn modify(
&mut self, &mut self,
modify_schema: UserModifySchema, modify_schema: UserModifySchema,
) -> Result<User, InstanceServerError> { ) -> Result<User, ChorusLibError> {
if modify_schema.new_password.is_some() if modify_schema.new_password.is_some()
|| modify_schema.email.is_some() || modify_schema.email.is_some()
|| modify_schema.code.is_some() || modify_schema.code.is_some()
{ {
return Err(InstanceServerError::PasswordRequiredError); return Err(ChorusLibError::PasswordRequiredError);
} }
let request = Client::new() let request = Client::new()
.patch(format!( .patch(format!(
@ -90,8 +87,8 @@ impl UserMeta {
/// ///
/// # Returns /// # Returns
/// ///
/// Returns `None` if the user was successfully deleted, or an `InstanceServerError` if an error occurred. /// Returns `None` if the user was successfully deleted, or an `ChorusLibError` if an error occurred.
pub async fn delete(mut self) -> Option<InstanceServerError> { pub async fn delete(mut self) -> Option<ChorusLibError> {
let mut belongs_to = self.belongs_to.borrow_mut(); let mut belongs_to = self.belongs_to.borrow_mut();
let request = Client::new() let request = Client::new()
.post(format!("{}/users/@me/delete/", belongs_to.urls.get_api())) .post(format!("{}/users/@me/delete/", belongs_to.urls.get_api()))
@ -113,10 +110,7 @@ impl UserMeta {
} }
impl User { impl User {
pub async fn get( pub async fn get(user: &mut UserMeta, id: Option<&String>) -> Result<User, ChorusLibError> {
user: &mut UserMeta,
id: Option<&String>,
) -> Result<User, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut(); let mut belongs_to = user.belongs_to.borrow_mut();
User::_get( User::_get(
&user.token(), &user.token(),
@ -132,7 +126,7 @@ impl User {
url_api: &str, url_api: &str,
limits_instance: &mut Limits, limits_instance: &mut Limits,
id: Option<&String>, id: Option<&String>,
) -> Result<User, InstanceServerError> { ) -> Result<User, ChorusLibError> {
let url: String; let url: String;
if id.is_none() { if id.is_none() {
url = format!("{}/users/@me/", url_api); url = format!("{}/users/@me/", url_api);
@ -163,7 +157,7 @@ impl User {
token: &String, token: &String,
url_api: &String, url_api: &String,
instance_limits: &mut Limits, instance_limits: &mut Limits,
) -> Result<UserSettings, InstanceServerError> { ) -> Result<UserSettings, ChorusLibError> {
let request: reqwest::RequestBuilder = Client::new() let request: reqwest::RequestBuilder = Client::new()
.get(format!("{}/users/@me/settings/", url_api)) .get(format!("{}/users/@me/settings/", url_api))
.bearer_auth(token); .bearer_auth(token);
@ -191,7 +185,7 @@ impl Instance {
* `token` - A valid access token for the API. * `token` - A valid access token for the API.
* `id` - The id of the user that will be retrieved. If this is None, the current user will be retrieved. * `id` - The id of the user that will be retrieved. If this is None, the current user will be retrieved.
# Errors # Errors
* [`InstanceServerError`] - If the request fails. * [`ChorusLibError`] - If the request fails.
# Notes # Notes
This function is a wrapper around [`User::get`]. This function is a wrapper around [`User::get`].
*/ */
@ -199,7 +193,7 @@ impl Instance {
&mut self, &mut self,
token: String, token: String,
id: Option<&String>, id: Option<&String>,
) -> Result<User, InstanceServerError> { ) -> Result<User, ChorusLibError> {
User::_get( User::_get(
&token, &token,
&self.urls.get_api().to_string(), &self.urls.get_api().to_string(),

View File

@ -11,7 +11,7 @@ custom_error! {
custom_error! { custom_error! {
#[derive(PartialEq, Eq)] #[derive(PartialEq, Eq)]
pub InstanceServerError pub ChorusLibError
NoResponse = "Did not receive a response from the Server.", NoResponse = "Did not receive a response from the Server.",
RequestErrorError{url:String, error:String} = "An error occured while trying to GET from {url}: {error}", RequestErrorError{url:String, error:String} = "An error occured while trying to GET from {url}: {error}",
ReceivedErrorCodeError{error_code:String} = "Received the following error code while requesting from the route: {error_code}", ReceivedErrorCodeError{error_code:String} = "Received the following error code while requesting from the route: {error_code}",

View File

@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::api::limits::Limits; use crate::api::limits::Limits;
use crate::errors::{FieldFormatError, InstanceServerError}; use crate::errors::{ChorusLibError, FieldFormatError};
use crate::types::{GeneralConfiguration, User, UserSettings}; use crate::types::{GeneralConfiguration, User, UserSettings};
use crate::URLBundle; use crate::URLBundle;
@ -26,7 +26,7 @@ impl Instance {
/// * `requester` - The [`LimitedRequester`] that will be used to make requests to the Spacebar server. /// * `requester` - The [`LimitedRequester`] that will be used to make requests to the Spacebar server.
/// # Errors /// # Errors
/// * [`InstanceError`] - If the instance cannot be created. /// * [`InstanceError`] - If the instance cannot be created.
pub async fn new(urls: URLBundle) -> Result<Instance, InstanceServerError> { pub async fn new(urls: URLBundle) -> Result<Instance, ChorusLibError> {
let mut instance = Instance { let mut instance = Instance {
urls: urls.clone(), urls: urls.clone(),
instance_info: GeneralConfiguration::new( instance_info: GeneralConfiguration::new(
@ -45,7 +45,7 @@ impl Instance {
instance.instance_info = match instance.general_configuration_schema().await { instance.instance_info = match instance.general_configuration_schema().await {
Ok(schema) => schema, Ok(schema) => schema,
Err(e) => { Err(e) => {
return Err(InstanceServerError::CantGetInfoError { return Err(ChorusLibError::CantGetInfoError {
error: e.to_string(), error: e.to_string(),
}) })
} }

View File

@ -1,6 +1,6 @@
use crate::{ use crate::{
api::limits::{Limit, LimitType, Limits, LimitsMutRef}, api::limits::{Limit, LimitType, Limits, LimitsMutRef},
errors::InstanceServerError, errors::ChorusLibError,
}; };
use reqwest::{Client, RequestBuilder, Response}; use reqwest::{Client, RequestBuilder, Response};
@ -71,12 +71,12 @@ impl LimitedRequester {
limit_type: LimitType, limit_type: LimitType,
instance_rate_limits: &mut Limits, instance_rate_limits: &mut Limits,
user_rate_limits: &mut Limits, user_rate_limits: &mut Limits,
) -> Result<Response, InstanceServerError> { ) -> Result<Response, ChorusLibError> {
if self.can_send_request(limit_type, instance_rate_limits, user_rate_limits) { if self.can_send_request(limit_type, instance_rate_limits, user_rate_limits) {
let built_request = match request.build() { let built_request = match request.build() {
Ok(request) => request, Ok(request) => request,
Err(e) => { Err(e) => {
return Err(InstanceServerError::RequestErrorError { return Err(ChorusLibError::RequestErrorError {
url: "".to_string(), url: "".to_string(),
error: e.to_string(), error: e.to_string(),
}) })
@ -86,7 +86,7 @@ impl LimitedRequester {
let response = match result { let response = match result {
Ok(is_response) => is_response, Ok(is_response) => is_response,
Err(e) => { Err(e) => {
return Err(InstanceServerError::ReceivedErrorCodeError { return Err(ChorusLibError::ReceivedErrorCodeError {
error_code: e.to_string(), error_code: e.to_string(),
}) })
} }
@ -99,10 +99,10 @@ impl LimitedRequester {
); );
if !response.status().is_success() { if !response.status().is_success() {
match response.status().as_u16() { match response.status().as_u16() {
401 => return Err(InstanceServerError::TokenExpired), 401 => return Err(ChorusLibError::TokenExpired),
403 => return Err(InstanceServerError::TokenExpired), 403 => return Err(ChorusLibError::TokenExpired),
_ => { _ => {
return Err(InstanceServerError::ReceivedErrorCodeError { return Err(ChorusLibError::ReceivedErrorCodeError {
error_code: response.status().as_str().to_string(), error_code: response.status().as_str().to_string(),
}) })
} }
@ -115,7 +115,7 @@ impl LimitedRequester {
request, request,
limit_type, limit_type,
}); });
Err(InstanceServerError::RateLimited { Err(ChorusLibError::RateLimited {
bucket: limit_type.to_string(), bucket: limit_type.to_string(),
}) })
} }
@ -302,7 +302,7 @@ mod rate_limit {
String::from("http://localhost:3001/cdn"), String::from("http://localhost:3001/cdn"),
); );
let mut requester = LimitedRequester::new().await; let mut requester = LimitedRequester::new().await;
let mut request: Option<Result<Response, InstanceServerError>> = None; let mut request: Option<Result<Response, ChorusLibError>> = None;
let mut instance_rate_limits = Limits::check_limits(urls.api.clone()).await; let mut instance_rate_limits = Limits::check_limits(urls.api.clone()).await;
let mut user_rate_limits = Limits::check_limits(urls.api.clone()).await; let mut user_rate_limits = Limits::check_limits(urls.api.clone()).await;

View File

@ -3,6 +3,8 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
/// Represents the schema which needs to be sent to create a Guild.
/// See: [https://docs.spacebar.chat/routes/#cmp--schemas-guildcreateschema](https://docs.spacebar.chat/routes/#cmp--schemas-guildcreateschema)
pub struct GuildCreateSchema { pub struct GuildCreateSchema {
pub name: Option<String>, pub name: Option<String>,
pub region: Option<String>, pub region: Option<String>,
@ -15,6 +17,8 @@ pub struct GuildCreateSchema {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
/// Represents the schema which needs to be sent to create or modify a Role.
/// See: [https://docs.spacebar.chat/routes/#cmp--schemas-rolemodifyschema](https://docs.spacebar.chat/routes/#cmp--schemas-rolemodifyschema)
pub struct RoleCreateModifySchema { pub struct RoleCreateModifySchema {
pub name: Option<String>, pub name: Option<String>,
pub permissions: Option<String>, pub permissions: Option<String>,
@ -28,6 +32,8 @@ pub struct RoleCreateModifySchema {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
/// Represents the schema which needs to be sent to update a roles' position.
/// See: [https://docs.spacebar.chat/routes/#cmp--schemas-rolepositionupdateschema](https://docs.spacebar.chat/routes/#cmp--schemas-rolepositionupdateschema)
pub struct RolePositionUpdateSchema { pub struct RolePositionUpdateSchema {
pub id: Snowflake, pub id: Snowflake,
pub position: i32, pub position: i32,