ChorusResult type alias

This commit is contained in:
Vincent Junge 2023-06-21 14:46:14 +02:00
parent 067d728874
commit f98180cd03
15 changed files with 70 additions and 79 deletions

View File

@ -5,16 +5,13 @@ use reqwest::Client;
use serde_json::{from_str, json};
use crate::api::limits::LimitType;
use crate::errors::ChorusLibError;
use crate::errors::{ChorusLibError, ChorusResult};
use crate::instance::{Instance, UserMeta};
use crate::limit::LimitedRequester;
use crate::types::{ErrorResponse, LoginResult, LoginSchema};
impl Instance {
pub async fn login_account(
&mut self,
login_schema: &LoginSchema,
) -> Result<UserMeta, ChorusLibError> {
pub async fn login_account(&mut self, login_schema: &LoginSchema) -> ChorusResult<UserMeta> {
let json_schema = json!(login_schema);
let client = Client::new();
let endpoint_url = self.urls.api.clone() + "/auth/login";

View File

@ -5,7 +5,7 @@ use serde_json::{from_str, json};
use crate::{
api::limits::LimitType,
errors::ChorusLibError,
errors::{ChorusLibError, ChorusResult},
instance::{Instance, Token, UserMeta},
limit::LimitedRequester,
types::{ErrorResponse, RegisterSchema},
@ -24,7 +24,7 @@ impl Instance {
pub async fn register_account(
&mut self,
register_schema: &RegisterSchema,
) -> Result<UserMeta, ChorusLibError> {
) -> ChorusResult<UserMeta> {
let json_schema = json!(register_schema);
let client = Client::new();
let endpoint_url = self.urls.api.clone() + "/auth/register";

View File

@ -3,13 +3,13 @@ use serde_json::to_string;
use crate::{
api::common,
errors::ChorusLibError,
errors::{ChorusLibError, ChorusResult},
instance::UserMeta,
types::{Channel, ChannelModifySchema, GetChannelMessagesSchema, Message, Snowflake},
};
impl Channel {
pub async fn get(user: &mut UserMeta, channel_id: &str) -> Result<Channel, ChorusLibError> {
pub async fn get(user: &mut UserMeta, channel_id: &str) -> ChorusResult<Channel> {
let url = user.belongs_to.borrow_mut().urls.api.clone();
let request = Client::new()
.get(format!("{}/channels/{}/", url, channel_id))
@ -43,7 +43,7 @@ impl Channel {
/// # Returns
///
/// A `Result` that contains a `ChorusLibError` if an error occurred during the request, or `()` if the request was successful.
pub async fn delete(self, user: &mut UserMeta) -> Result<(), ChorusLibError> {
pub async fn delete(self, user: &mut UserMeta) -> ChorusResult<()> {
let request = Client::new()
.delete(format!(
"{}/channels/{}/",
@ -73,7 +73,7 @@ impl Channel {
modify_data: ChannelModifySchema,
channel_id: Snowflake,
user: &mut UserMeta,
) -> Result<Channel, ChorusLibError> {
) -> ChorusResult<Channel> {
let request = Client::new()
.patch(format!(
"{}/channels/{}/",

View File

@ -3,7 +3,7 @@ use serde_json::to_string;
use crate::{
api::handle_request_as_result,
errors::ChorusLibError,
errors::{ChorusLibError, ChorusResult},
instance::UserMeta,
types::{self, PermissionOverwrite, Snowflake},
};
@ -24,7 +24,7 @@ impl types::Channel {
user: &mut UserMeta,
channel_id: Snowflake,
overwrite: PermissionOverwrite,
) -> Result<(), ChorusLibError> {
) -> ChorusResult<()> {
let url = {
format!(
"{}/channels/{}/permissions/{}",
@ -60,7 +60,7 @@ impl types::Channel {
user: &mut UserMeta,
channel_id: Snowflake,
overwrite_id: Snowflake,
) -> Result<(), ChorusLibError> {
) -> ChorusResult<()> {
let url = format!(
"{}/channels/{}/permissions/{}",
user.belongs_to.borrow_mut().urls.api,

View File

@ -1,6 +1,6 @@
use reqwest::Client;
use crate::{api::handle_request_as_result, errors::ChorusLibError, instance::UserMeta, types};
use crate::{api::handle_request_as_result, errors::ChorusResult, instance::UserMeta, types};
/**
Useful metadata for working with [`types::Reaction`], bundled together nicely.
@ -25,7 +25,7 @@ impl ReactionMeta {
# Reference
See [https://discord.com/developers/docs/resources/channel#delete-all-reactions](https://discord.com/developers/docs/resources/channel#delete-all-reactions)
*/
pub async fn delete_all(&self, user: &mut UserMeta) -> Result<(), ChorusLibError> {
pub async fn delete_all(&self, user: &mut UserMeta) -> ChorusResult<()> {
let url = format!(
"{}/channels/{}/messages/{}/reactions/",
user.belongs_to.borrow().urls.api,
@ -51,7 +51,7 @@ impl ReactionMeta {
# Reference
See [https://discord.com/developers/docs/resources/channel#get-reactions](https://discord.com/developers/docs/resources/channel#get-reactions)
*/
pub async fn get(&self, emoji: &str, user: &mut UserMeta) -> Result<(), ChorusLibError> {
pub async fn get(&self, emoji: &str, user: &mut UserMeta) -> ChorusResult<()> {
let url = format!(
"{}/channels/{}/messages/{}/reactions/{}/",
user.belongs_to.borrow().urls.api,
@ -80,11 +80,7 @@ impl ReactionMeta {
# Reference
See [https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji](https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji)
*/
pub async fn delete_emoji(
&self,
emoji: &str,
user: &mut UserMeta,
) -> Result<(), ChorusLibError> {
pub async fn delete_emoji(&self, emoji: &str, user: &mut UserMeta) -> ChorusResult<()> {
let url = format!(
"{}/channels/{}/messages/{}/reactions/{}/",
user.belongs_to.borrow().urls.api,
@ -115,7 +111,7 @@ impl ReactionMeta {
# Reference
See [https://discord.com/developers/docs/resources/channel#create-reaction](https://discord.com/developers/docs/resources/channel#create-reaction)
*/
pub async fn create(&self, emoji: &str, user: &mut UserMeta) -> Result<(), ChorusLibError> {
pub async fn create(&self, emoji: &str, user: &mut UserMeta) -> ChorusResult<()> {
let url = format!(
"{}/channels/{}/messages/{}/reactions/{}/@me/",
user.belongs_to.borrow().urls.api,
@ -143,7 +139,7 @@ impl ReactionMeta {
# Reference
See [https://discord.com/developers/docs/resources/channel#delete-own-reaction](https://discord.com/developers/docs/resources/channel#delete-own-reaction)
*/
pub async fn remove(&self, emoji: &str, user: &mut UserMeta) -> Result<(), ChorusLibError> {
pub async fn remove(&self, emoji: &str, user: &mut UserMeta) -> ChorusResult<()> {
let url = format!(
"{}/channels/{}/messages/{}/reactions/{}/@me/",
user.belongs_to.borrow().urls.api,
@ -179,7 +175,7 @@ impl ReactionMeta {
user_id: &str,
emoji: &str,
user: &mut UserMeta,
) -> Result<(), ChorusLibError> {
) -> ChorusResult<()> {
let url = format!(
"{}/channels/{}/messages/{}/reactions/{}/{}",
user.belongs_to.borrow().urls.api,

View File

@ -2,7 +2,11 @@ use reqwest::RequestBuilder;
use serde::Deserialize;
use serde_json::from_str;
use crate::{errors::ChorusLibError, instance::UserMeta, limit::LimitedRequester};
use crate::{
errors::{ChorusLibError, ChorusResult},
instance::UserMeta,
limit::LimitedRequester,
};
use super::limits::LimitType;
@ -27,7 +31,7 @@ pub async fn handle_request_as_result(
request: RequestBuilder,
user: &mut UserMeta,
limit_type: LimitType,
) -> Result<(), ChorusLibError> {
) -> ChorusResult<()> {
match handle_request(request, user, limit_type).await {
Ok(_) => Ok(()),
Err(e) => Err(ChorusLibError::InvalidResponseError {
@ -40,7 +44,7 @@ pub async fn deserialize_response<T: for<'a> Deserialize<'a>>(
request: RequestBuilder,
user: &mut UserMeta,
limit_type: LimitType,
) -> Result<T, ChorusLibError> {
) -> ChorusResult<T> {
let response = handle_request(request, user, limit_type).await.unwrap();
let response_text = match response.text().await {
Ok(string) => string,

View File

@ -7,6 +7,7 @@ use crate::api::handle_request;
use crate::api::handle_request_as_result;
use crate::api::limits::Limits;
use crate::errors::ChorusLibError;
use crate::errors::ChorusResult;
use crate::instance::Instance;
use crate::instance::UserMeta;
use crate::limit::LimitedRequester;
@ -32,7 +33,7 @@ impl Guild {
pub async fn create(
user: &mut UserMeta,
guild_create_schema: GuildCreateSchema,
) -> Result<Guild, ChorusLibError> {
) -> ChorusResult<Guild> {
let url = format!("{}/guilds/", user.belongs_to.borrow().urls.api);
let request = reqwest::Client::new()
.post(url.clone())
@ -65,7 +66,7 @@ impl Guild {
/// None => println!("Guild deleted successfully"),
/// }
/// ```
pub async fn delete(user: &mut UserMeta, guild_id: &str) -> Result<(), ChorusLibError> {
pub async fn delete(user: &mut UserMeta, guild_id: &str) -> ChorusResult<()> {
let url = format!(
"{}/guilds/{}/delete/",
user.belongs_to.borrow().urls.api,
@ -94,7 +95,7 @@ impl Guild {
&self,
user: &mut UserMeta,
schema: ChannelCreateSchema,
) -> Result<Channel, ChorusLibError> {
) -> ChorusResult<Channel> {
let mut belongs_to = user.belongs_to.borrow_mut();
Channel::_create(
&user.token,
@ -116,7 +117,7 @@ impl Guild {
/// * `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.
///
pub async fn channels(&self, user: &mut UserMeta) -> Result<Vec<Channel>, ChorusLibError> {
pub async fn channels(&self, user: &mut UserMeta) -> ChorusResult<Vec<Channel>> {
let request = Client::new()
.get(format!(
"{}/guilds/{}/channels/",
@ -155,7 +156,7 @@ impl Guild {
/// * `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.
///
pub async fn get(user: &mut UserMeta, guild_id: &str) -> Result<Guild, ChorusLibError> {
pub async fn get(user: &mut UserMeta, guild_id: &str) -> ChorusResult<Guild> {
let mut belongs_to = user.belongs_to.borrow_mut();
Guild::_get(
&format!("{}", belongs_to.urls.api),
@ -175,7 +176,7 @@ impl Guild {
token: &str,
limits_user: &mut Limits,
instance: &mut Instance,
) -> Result<Guild, ChorusLibError> {
) -> ChorusResult<Guild> {
let request = Client::new()
.get(format!("{}/guilds/{}/", url_api, guild_id))
.bearer_auth(token);
@ -214,7 +215,7 @@ impl Channel {
user: &mut UserMeta,
guild_id: &str,
schema: ChannelCreateSchema,
) -> Result<Channel, ChorusLibError> {
) -> ChorusResult<Channel> {
let mut belongs_to = user.belongs_to.borrow_mut();
Channel::_create(
&user.token,
@ -234,7 +235,7 @@ impl Channel {
schema: ChannelCreateSchema,
limits_user: &mut Limits,
instance: &mut Instance,
) -> Result<Channel, ChorusLibError> {
) -> ChorusResult<Channel> {
let request = Client::new()
.post(format!("{}/guilds/{}/channels/", url_api, guild_id))
.bearer_auth(token)

View File

@ -2,7 +2,7 @@ use reqwest::Client;
use crate::{
api::{deserialize_response, handle_request_as_result},
errors::ChorusLibError,
errors::ChorusResult,
instance::UserMeta,
types,
};
@ -23,7 +23,7 @@ impl types::GuildMember {
user: &mut UserMeta,
guild_id: &str,
member_id: &str,
) -> Result<types::GuildMember, ChorusLibError> {
) -> ChorusResult<types::GuildMember> {
let url = format!(
"{}/guilds/{}/members/{}/",
user.belongs_to.borrow().urls.api,
@ -56,7 +56,7 @@ impl types::GuildMember {
guild_id: &str,
member_id: &str,
role_id: &str,
) -> Result<(), ChorusLibError> {
) -> ChorusResult<()> {
let url = format!(
"{}/guilds/{}/members/{}/roles/{}/",
user.belongs_to.borrow().urls.api,

View File

@ -3,7 +3,7 @@ use serde_json::to_string;
use crate::{
api::deserialize_response,
errors::ChorusLibError,
errors::{ChorusLibError, ChorusResult},
instance::UserMeta,
types::{self, RoleCreateModifySchema, RoleObject},
};
@ -26,7 +26,7 @@ impl types::RoleObject {
pub async fn get_all(
user: &mut UserMeta,
guild_id: &str,
) -> Result<Option<Vec<RoleObject>>, ChorusLibError> {
) -> ChorusResult<Option<Vec<RoleObject>>> {
let url = format!(
"{}/guilds/{}/roles/",
user.belongs_to.borrow().urls.api,
@ -65,7 +65,7 @@ impl types::RoleObject {
user: &mut UserMeta,
guild_id: &str,
role_id: &str,
) -> Result<RoleObject, ChorusLibError> {
) -> ChorusResult<RoleObject> {
let url = format!(
"{}/guilds/{}/roles/{}/",
user.belongs_to.borrow().urls.api,
@ -95,7 +95,7 @@ impl types::RoleObject {
user: &mut UserMeta,
guild_id: &str,
role_create_schema: RoleCreateModifySchema,
) -> Result<RoleObject, ChorusLibError> {
) -> ChorusResult<RoleObject> {
let url = format!(
"{}/guilds/{}/roles/",
user.belongs_to.borrow().urls.api,
@ -129,7 +129,7 @@ impl types::RoleObject {
user: &mut UserMeta,
guild_id: &str,
role_position_update_schema: types::RolePositionUpdateSchema,
) -> Result<RoleObject, ChorusLibError> {
) -> ChorusResult<RoleObject> {
let url = format!(
"{}/guilds/{}/roles/",
user.belongs_to.borrow().urls.api,
@ -169,7 +169,7 @@ impl types::RoleObject {
guild_id: &str,
role_id: &str,
role_create_schema: RoleCreateModifySchema,
) -> Result<RoleObject, ChorusLibError> {
) -> ChorusResult<RoleObject> {
let url = format!(
"{}/guilds/{}/roles/{}",
user.belongs_to.borrow().urls.api,

View File

@ -1,7 +1,7 @@
use reqwest::Client;
use serde_json::from_str;
use crate::errors::ChorusLibError;
use crate::errors::{ChorusLibError, ChorusResult};
use crate::instance::Instance;
use crate::types::GeneralConfiguration;
@ -9,9 +9,7 @@ impl Instance {
/// Gets the instance policies schema.
/// # Errors
/// [`ChorusLibError`] - If the request fails.
pub async fn general_configuration_schema(
&self,
) -> Result<GeneralConfiguration, ChorusLibError> {
pub async fn general_configuration_schema(&self) -> ChorusResult<GeneralConfiguration> {
let client = Client::new();
let endpoint_url = self.urls.api.clone() + "/policies/instance/";
let request = match client.get(&endpoint_url).send().await {

View File

@ -3,7 +3,7 @@ use serde_json::to_string;
use crate::{
api::{deserialize_response, handle_request_as_result},
errors::ChorusLibError,
errors::ChorusResult,
instance::UserMeta,
types::{self, CreateUserRelationshipSchema, RelationshipType},
};
@ -16,11 +16,11 @@ impl UserMeta {
/// * `user_id` - A string slice that holds the ID of the user to retrieve the mutual relationships with.
///
/// # Returns
/// This function returns a [`Result<Vec<PublicUser>, ChorusLibError>`].
/// This function returns a [`ChorusResult<Vec<PublicUser>>`].
pub async fn get_mutual_relationships(
&mut self,
user_id: &str,
) -> Result<Vec<types::PublicUser>, ChorusLibError> {
) -> ChorusResult<Vec<types::PublicUser>> {
let url = format!(
"{}/users/{}/relationships/",
self.belongs_to.borrow().urls.api,
@ -38,8 +38,8 @@ impl UserMeta {
/// Retrieves the authenticated user's relationships.
///
/// # Returns
/// This function returns a [`Result<Vec<types::Relationship>, ChorusLibError>`].
pub async fn get_relationships(&mut self) -> Result<Vec<types::Relationship>, ChorusLibError> {
/// This function returns a [`ChorusResult<Vec<types::Relationship>>`].
pub async fn get_relationships(&mut self) -> ChorusResult<Vec<types::Relationship>> {
let url = format!(
"{}/users/@me/relationships/",
self.belongs_to.borrow().urls.api
@ -64,7 +64,7 @@ impl UserMeta {
pub async fn send_friend_request(
&mut self,
schema: types::FriendRequestSendSchema,
) -> Result<(), ChorusLibError> {
) -> ChorusResult<()> {
let url = format!(
"{}/users/@me/relationships/",
self.belongs_to.borrow().urls.api
@ -92,7 +92,7 @@ impl UserMeta {
&mut self,
user_id: &str,
relationship_type: RelationshipType,
) -> Result<(), ChorusLibError> {
) -> ChorusResult<()> {
let api_url = self.belongs_to.borrow().urls.api.clone();
match relationship_type {
RelationshipType::None => {
@ -137,7 +137,7 @@ impl UserMeta {
///
/// # Returns
/// This function returns a [`Result`] that holds a [`ChorusLibError`] if the request fails.
pub async fn remove_relationship(&mut self, user_id: &str) -> Result<(), ChorusLibError> {
pub async fn remove_relationship(&mut self, user_id: &str) -> ChorusResult<()> {
let url = format!(
"{}/users/@me/relationships/{}/",
self.belongs_to.borrow().urls.api,

View File

@ -2,8 +2,8 @@ use reqwest::Client;
use serde_json::to_string;
use crate::{
api::{deserialize_response, handle_request_as_result, limits::Limits},
errors::ChorusLibError,
api::{deserialize_response, handle_request_as_result},
errors::{ChorusLibError, ChorusResult},
instance::{Instance, UserMeta},
limit::LimitedRequester,
types::{User, UserModifySchema, UserSettings},
@ -22,7 +22,7 @@ impl UserMeta {
/// # Errors
///
/// * [`ChorusLibError`] - If the request fails.
pub async fn get(user: &mut UserMeta, id: Option<&String>) -> Result<User, ChorusLibError> {
pub async fn get(user: &mut UserMeta, id: Option<&String>) -> ChorusResult<User> {
User::get(user, id).await
}
@ -30,7 +30,7 @@ impl UserMeta {
token: &String,
url_api: &String,
instance: &mut Instance,
) -> Result<UserSettings, ChorusLibError> {
) -> ChorusResult<UserSettings> {
User::get_settings(token, url_api, instance).await
}
@ -43,10 +43,7 @@ impl UserMeta {
/// # Errors
///
/// Returns an `ChorusLibError` if the request fails or if a password is required but not provided.
pub async fn modify(
&mut self,
modify_schema: UserModifySchema,
) -> Result<User, ChorusLibError> {
pub async fn modify(&mut self, modify_schema: UserModifySchema) -> ChorusResult<User> {
if modify_schema.new_password.is_some()
|| modify_schema.email.is_some()
|| modify_schema.code.is_some()
@ -74,7 +71,7 @@ impl UserMeta {
/// # Returns
///
/// Returns `()` if the user was successfully deleted, or a `ChorusLibError` if an error occurred.
pub async fn delete(mut self) -> Result<(), ChorusLibError> {
pub async fn delete(mut self) -> ChorusResult<()> {
let request = Client::new()
.post(format!(
"{}/users/@me/delete/",
@ -86,7 +83,7 @@ impl UserMeta {
}
impl User {
pub async fn get(user: &mut UserMeta, id: Option<&String>) -> Result<User, ChorusLibError> {
pub async fn get(user: &mut UserMeta, id: Option<&String>) -> ChorusResult<User> {
let mut belongs_to = user.belongs_to.borrow_mut();
User::_get(
&user.token(),
@ -102,7 +99,7 @@ impl User {
url_api: &str,
instance: &mut Instance,
id: Option<&String>,
) -> Result<User, ChorusLibError> {
) -> ChorusResult<User> {
let url = if id.is_none() {
format!("{}/users/@me/", url_api)
} else {
@ -130,7 +127,7 @@ impl User {
token: &String,
url_api: &String,
instance: &mut Instance,
) -> Result<UserSettings, ChorusLibError> {
) -> ChorusResult<UserSettings> {
let request: reqwest::RequestBuilder = Client::new()
.get(format!("{}/users/@me/settings/", url_api))
.bearer_auth(token);
@ -160,11 +157,7 @@ impl Instance {
# Notes
This function is a wrapper around [`User::get`].
*/
pub async fn get_user(
&mut self,
token: String,
id: Option<&String>,
) -> Result<User, ChorusLibError> {
pub async fn get_user(&mut self, token: String, id: Option<&String>) -> ChorusResult<User> {
User::_get(&token, &self.urls.api.clone(), self, id).await
}
}

View File

@ -9,6 +9,8 @@ custom_error! {
EmailError = "The provided email address is in an invalid format.",
}
pub type ChorusResult<T> = std::result::Result<T, ChorusLibError>;
custom_error! {
#[derive(PartialEq, Eq)]
pub ChorusLibError

View File

@ -6,7 +6,7 @@ use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::api::limits::Limits;
use crate::errors::{ChorusLibError, FieldFormatError};
use crate::errors::{ChorusLibError, ChorusResult, FieldFormatError};
use crate::types::{GeneralConfiguration, User, UserSettings};
use crate::UrlBundle;
@ -28,7 +28,7 @@ impl Instance {
/// * `requester` - The [`LimitedRequester`] that will be used to make requests to the Spacebar server.
/// # Errors
/// * [`InstanceError`] - If the instance cannot be created.
pub async fn new(urls: UrlBundle) -> Result<Instance, ChorusLibError> {
pub async fn new(urls: UrlBundle) -> ChorusResult<Instance> {
let mut instance = Instance {
urls: urls.clone(),
// Will be overwritten in the next step

View File

@ -2,7 +2,7 @@ use reqwest::{RequestBuilder, Response};
use crate::{
api::limits::{Limit, LimitType, Limits, LimitsMutRef},
errors::ChorusLibError,
errors::{ChorusLibError, ChorusResult},
instance::Instance,
};
@ -43,7 +43,7 @@ impl LimitedRequester {
limit_type: LimitType,
instance: &mut Instance,
user_rate_limits: &mut Limits,
) -> Result<Response, ChorusLibError> {
) -> ChorusResult<Response> {
if LimitedRequester::can_send_request(limit_type, &instance.limits, user_rate_limits) {
let built_request = match request.build() {
Ok(request) => request,
@ -256,7 +256,7 @@ mod rate_limit {
String::from("wss://localhost:3001/"),
String::from("http://localhost:3001/cdn"),
);
let mut request: Option<Result<Response, ChorusLibError>> = None;
let mut request: Option<ChorusResult<Response>> = None;
let mut instance = Instance::new(urls.clone()).await.unwrap();
let mut user_rate_limits = Limits::check_limits(urls.api.clone()).await;