Merge pull request #83 from polyphony-chat/refactor/less-boilerplate

Refactor/less boilerplate
This commit is contained in:
Flori 2023-05-30 23:11:47 +02:00 committed by GitHub
commit b87ac84f61
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 148 additions and 163 deletions

View File

@ -4,28 +4,31 @@ use serde_json::{from_str, to_string};
use crate::{
api::limits::Limits,
errors::InstanceServerError,
instance::UserMeta,
limit::LimitedRequester,
types::{Channel, ChannelModifySchema},
};
impl Channel {
pub async fn get(
token: &str,
url_api: &str,
user: &mut UserMeta,
channel_id: &str,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Result<Channel, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
let request = Client::new()
.get(format!("{}/channels/{}/", url_api, channel_id))
.bearer_auth(token);
.get(format!(
"{}/channels/{}/",
belongs_to.urls.get_api(),
channel_id
))
.bearer_auth(user.token());
let mut requester = LimitedRequester::new().await;
let result = match requester
.send_request(
request,
crate::api::limits::LimitType::Guild,
limits_instance,
limits_user,
&mut belongs_to.limits,
&mut user.limits,
)
.await
{
@ -36,7 +39,7 @@ impl Channel {
match from_str::<Channel>(&result_text) {
Ok(object) => Ok(object),
Err(e) => Err(InstanceServerError::RequestErrorError {
url: format!("{}/channels/{}/", url_api, channel_id),
url: format!("{}/channels/{}/", belongs_to.urls.get_api(), channel_id),
error: e.to_string(),
}),
}
@ -55,23 +58,22 @@ impl Channel {
/// # Returns
///
/// An `Option` that contains an `InstanceServerError` if an error occurred during the request, or `None` if the request was successful.
pub async fn delete(
self,
token: &str,
url_api: &str,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Option<InstanceServerError> {
pub async fn delete(self, user: &mut UserMeta) -> Option<InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
let request = Client::new()
.delete(format!("{}/channels/{}/", url_api, self.id.to_string()))
.bearer_auth(token);
.delete(format!(
"{}/channels/{}/",
belongs_to.urls.get_api(),
self.id.to_string()
))
.bearer_auth(user.token());
match LimitedRequester::new()
.await
.send_request(
request,
crate::api::limits::LimitType::Channel,
limits_instance,
limits_user,
&mut belongs_to.limits,
&mut user.limits,
)
.await
{
@ -96,23 +98,25 @@ impl Channel {
/// A `Result` that contains a `Channel` object if the request was successful, or an `InstanceServerError` if an error occurred during the request.
pub async fn modify(
modify_data: ChannelModifySchema,
token: &str,
url_api: &str,
channel_id: &str,
limits_user: &mut Limits,
limits_instance: &mut Limits,
user: &mut UserMeta,
) -> Result<Channel, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
let request = Client::new()
.patch(format!("{}/channels/{}/", url_api, channel_id))
.bearer_auth(token)
.patch(format!(
"{}/channels/{}/",
belongs_to.urls.get_api(),
channel_id
))
.bearer_auth(user.token())
.body(to_string(&modify_data).unwrap());
let channel = match LimitedRequester::new()
.await
.send_request(
request,
crate::api::limits::LimitType::Channel,
limits_instance,
limits_user,
&mut belongs_to.limits,
&mut user.limits,
)
.await
{

View File

@ -4,7 +4,6 @@ pub mod messages {
use reqwest::{multipart, Client};
use serde_json::to_string;
use crate::api::limits::Limits;
use crate::instance::UserMeta;
use crate::limit::LimitedRequester;
use crate::types::{Message, MessageSendSchema, PartialDiscordFileAttachment};
@ -21,28 +20,27 @@ pub mod messages {
# Errors
* [`InstanceServerError`] - If the message cannot be sent.
*/
pub async fn send<'a>(
url_api: String,
pub async fn send(
user: &mut UserMeta,
channel_id: String,
message: &mut MessageSendSchema,
files: Option<Vec<PartialDiscordFileAttachment>>,
token: String,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
let url_api = belongs_to.urls.get_api();
let mut requester = LimitedRequester::new().await;
if files.is_none() {
let message_request = Client::new()
.post(format!("{}/channels/{}/messages/", url_api, channel_id))
.bearer_auth(token)
.bearer_auth(user.token())
.body(to_string(message).unwrap());
requester
.send_request(
message_request,
crate::api::limits::LimitType::Channel,
limits_instance,
limits_user,
&mut belongs_to.limits,
&mut user.limits,
)
.await
} else {
@ -75,15 +73,15 @@ pub mod messages {
let message_request = Client::new()
.post(format!("{}/channels/{}/messages/", url_api, channel_id))
.bearer_auth(token)
.bearer_auth(user.token())
.multipart(form);
requester
.send_request(
message_request,
crate::api::limits::LimitType::Channel,
limits_instance,
limits_user,
&mut belongs_to.limits,
&mut user.limits,
)
.await
}
@ -91,24 +89,25 @@ pub mod messages {
}
impl UserMeta {
/// Shorthand call for Message::send()
/**
Sends a message to the Spacebar server.
# Arguments
* `url_api` - The URL of the Spacebar server's API.
* `message` - The [`Message`] that will be sent to the Spacebar server.
* `limits_user` - The [`Limits`] of the user.
* `limits_instance` - The [`Limits`] of the instance.
* `requester` - The [`LimitedRequester`] that will be used to make requests to the Spacebar server.
# Errors
* [`InstanceServerError`] - If the message cannot be sent.
*/
pub async fn send_message(
&mut self,
message: &mut MessageSendSchema,
channel_id: String,
files: Option<Vec<PartialDiscordFileAttachment>>,
) -> Result<reqwest::Response, crate::errors::InstanceServerError> {
let token = self.token().clone();
let mut belongs_to = self.belongs_to.borrow_mut();
Message::send(
belongs_to.urls.get_api().to_string(),
channel_id,
message,
files,
token,
&mut self.limits,
&mut belongs_to.limits,
)
.await
Message::send(self, channel_id, message, files).await
}
}
}

View File

@ -27,12 +27,10 @@ impl Guild {
///
pub async fn create(
user: &mut UserMeta,
url_api: &str,
guild_create_schema: GuildCreateSchema,
) -> Result<Guild, crate::errors::InstanceServerError> {
let url = format!("{}/guilds/", url_api);
let mut limits_user = user.limits.get_as_mut();
let mut limits_instance = &mut user.belongs_to.borrow_mut().limits;
let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!("{}/guilds/", belongs_to.urls.get_api());
let request = reqwest::Client::new()
.post(url.clone())
.bearer_auth(user.token.clone())
@ -42,8 +40,8 @@ impl Guild {
.send_request(
request,
crate::api::limits::LimitType::Guild,
limits_instance,
limits_user,
&mut belongs_to.limits,
&mut user.limits,
)
.await
{
@ -51,12 +49,12 @@ impl Guild {
Err(e) => return Err(e),
};
let id: GuildCreateResponse = from_str(&result.text().await.unwrap()).unwrap();
let guild = Guild::get(
url_api,
let guild = Guild::_get(
belongs_to.clone().urls.get_api(),
&id.id,
&user.token,
&mut limits_user,
&mut limits_instance,
&mut user.limits,
&mut belongs_to.limits,
)
.await
.unwrap();
@ -87,14 +85,9 @@ impl Guild {
/// None => println!("Guild deleted successfully"),
/// }
/// ```
pub async fn delete(
user: &mut UserMeta,
url_api: &str,
guild_id: &str,
) -> Option<InstanceServerError> {
let url = format!("{}/guilds/{}/delete/", url_api, guild_id);
let limits_user = user.limits.get_as_mut();
let limits_instance = &mut user.belongs_to.borrow_mut().limits;
pub async fn delete(user: &mut UserMeta, guild_id: &str) -> Option<InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
let url = format!("{}/guilds/{}/delete/", belongs_to.urls.get_api(), guild_id);
let request = reqwest::Client::new()
.post(url.clone())
.bearer_auth(user.token.clone());
@ -103,8 +96,8 @@ impl Guild {
.send_request(
request,
crate::api::limits::LimitType::Guild,
limits_instance,
limits_user,
&mut belongs_to.limits,
&mut user.limits,
)
.await;
if result.is_err() {
@ -129,19 +122,17 @@ impl Guild {
/// A `Result` containing a `reqwest::Response` if the request was successful, or an `InstanceServerError` if there was an error.
pub async fn create_channel(
&self,
url_api: &str,
token: &str,
user: &mut UserMeta,
schema: ChannelCreateSchema,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Result<Channel, InstanceServerError> {
Channel::create(
token,
url_api,
let mut belongs_to = user.belongs_to.borrow_mut();
Channel::_create(
&user.token,
&format!("{}", belongs_to.urls.get_api()),
&self.id.to_string(),
schema,
limits_user,
limits_instance,
&mut user.limits,
&mut belongs_to.limits,
)
.await
}
@ -155,27 +146,22 @@ 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,
url_api: &str,
token: &str,
limits_user: &mut Limits,
limits_instance: &mut Limits,
) -> Result<Vec<Channel>, InstanceServerError> {
pub async fn channels(&self, user: &mut UserMeta) -> Result<Vec<Channel>, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
let request = Client::new()
.get(format!(
"{}/guilds/{}/channels/",
url_api,
belongs_to.urls.get_api(),
self.id.to_string()
))
.bearer_auth(token);
.bearer_auth(user.token());
let result = match LimitedRequester::new()
.await
.send_request(
request,
crate::api::limits::LimitType::Guild,
limits_instance,
limits_user,
&mut belongs_to.limits,
&mut user.limits,
)
.await
{
@ -210,7 +196,21 @@ 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(
pub async fn get(user: &mut UserMeta, guild_id: &str) -> Result<Guild, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
Guild::_get(
&format!("{}", belongs_to.urls.get_api()),
guild_id,
&user.token,
&mut user.limits,
&mut belongs_to.limits,
)
.await
}
/// For internal use. Does the same as the public get method, but does not require a second, mutable
/// borrow of `UserMeta::belongs_to`, when used in conjunction with other methods, which borrow `UserMeta::belongs_to`.
async fn _get(
url_api: &str,
guild_id: &str,
token: &str,
@ -254,6 +254,23 @@ impl Channel {
///
/// A `Result` containing a `reqwest::Response` if the request was successful, or an `InstanceServerError` if there was an error.
pub async fn create(
user: &mut UserMeta,
guild_id: &str,
schema: ChannelCreateSchema,
) -> Result<Channel, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
Channel::_create(
&user.token,
&format!("{}", belongs_to.urls.get_api()),
guild_id,
schema,
&mut user.limits,
&mut belongs_to.limits,
)
.await
}
async fn _create(
token: &str,
url_api: &str,
guild_id: &str,

View File

@ -21,12 +21,10 @@ impl UserMeta {
* [`InstanceServerError`] - If the request fails.
*/
pub async fn get(
token: &String,
url_api: &String,
user: &mut UserMeta,
id: Option<&String>,
instance_limits: &mut Limits,
) -> Result<User, InstanceServerError> {
User::get(token, url_api, id, instance_limits).await
User::get(user, id).await
}
pub async fn get_settings(
@ -116,10 +114,24 @@ impl UserMeta {
impl User {
pub async fn get(
token: &String,
url_api: &String,
user: &mut UserMeta,
id: Option<&String>,
) -> Result<User, InstanceServerError> {
let mut belongs_to = user.belongs_to.borrow_mut();
User::_get(
&user.token(),
&format!("{}", belongs_to.urls.get_api()),
&mut belongs_to.limits,
id,
)
.await
}
async fn _get(
token: &str,
url_api: &str,
limits_instance: &mut Limits,
id: Option<&String>,
instance_limits: &mut Limits,
) -> Result<User, InstanceServerError> {
let url: String;
if id.is_none() {
@ -129,12 +141,12 @@ impl User {
}
let request = reqwest::Client::new().get(url).bearer_auth(token);
let mut requester = crate::limit::LimitedRequester::new().await;
let mut cloned_limits = instance_limits.clone();
let mut cloned_limits = limits_instance.clone();
match requester
.send_request(
request,
crate::api::limits::LimitType::Ip,
instance_limits,
limits_instance,
&mut cloned_limits,
)
.await
@ -188,11 +200,11 @@ impl Instance {
token: String,
id: Option<&String>,
) -> Result<User, InstanceServerError> {
UserMeta::get(
User::_get(
&token,
&self.urls.get_api().to_string(),
id,
&mut self.limits,
id,
)
.await
}

View File

@ -5,19 +5,13 @@ use chorus::types::{self, Channel};
async fn get_channel() {
let mut bundle = common::setup().await;
let bundle_channel = bundle.channel.clone();
let bundle_user = &mut bundle.user;
let mut bundle_user = &mut bundle.user;
assert_eq!(
bundle_channel,
Channel::get(
bundle_user.token.as_str(),
bundle.instance.urls.get_api(),
&bundle_channel.id.to_string(),
&mut bundle_user.limits,
&mut bundle.instance.limits
)
.await
.unwrap()
Channel::get(&mut bundle_user, &bundle_channel.id.to_string(),)
.await
.unwrap()
);
common::teardown(bundle).await
}
@ -25,16 +19,7 @@ async fn get_channel() {
#[tokio::test]
async fn delete_channel() {
let mut bundle = common::setup().await;
let result = bundle
.channel
.clone()
.delete(
&bundle.user.token,
bundle.instance.urls.get_api(),
&mut bundle.user.limits,
&mut bundle.instance.limits,
)
.await;
let result = bundle.channel.clone().delete(&mut bundle.user).await;
assert!(result.is_none());
common::teardown(bundle).await
}
@ -63,11 +48,8 @@ async fn modify_channel() {
};
let result = Channel::modify(
modify_data,
&bundle.user.token,
bundle.instance.urls.get_api(),
&bundle.channel.id.to_string(),
&mut bundle.user.limits,
&mut bundle.instance.limits,
&mut bundle.user,
)
.await
.unwrap();

View File

@ -65,19 +65,10 @@ pub async fn setup() -> TestBundle {
video_quality_mode: None,
};
let mut user = instance.register_account(&reg).await.unwrap();
let guild = Guild::create(&mut user, urls.get_api(), guild_create_schema)
let guild = Guild::create(&mut user, guild_create_schema).await.unwrap();
let channel = Channel::create(&mut user, &guild.id.to_string(), channel_create_schema)
.await
.unwrap();
let channel = Channel::create(
&user.token,
urls.get_api(),
&guild.id.to_string(),
channel_create_schema,
&mut user.limits,
&mut instance.limits,
)
.await
.unwrap();
TestBundle {
urls,
@ -90,11 +81,6 @@ pub async fn setup() -> TestBundle {
// Teardown method to clean up after a test.
pub async fn teardown(mut bundle: TestBundle) {
Guild::delete(
&mut bundle.user,
bundle.instance.urls.get_api(),
&bundle.guild.id.to_string(),
)
.await;
Guild::delete(&mut bundle.user, &bundle.guild.id.to_string()).await;
bundle.user.delete().await;
}

View File

@ -15,17 +15,11 @@ async fn guild_creation_deletion() {
rules_channel_id: None,
};
let guild = Guild::create(&mut bundle.user, bundle.urls.get_api(), guild_create_schema)
let guild = Guild::create(&mut bundle.user, guild_create_schema)
.await
.unwrap();
match Guild::delete(
&mut bundle.user,
bundle.urls.get_api(),
&guild.id.to_string(),
)
.await
{
match Guild::delete(&mut bundle.user, &guild.id.to_string()).await {
None => assert!(true),
Some(_) => assert!(false),
}
@ -37,16 +31,7 @@ async fn get_channels() {
let mut bundle = common::setup().await;
println!(
"{:?}",
bundle
.guild
.channels(
bundle.instance.urls.get_api(),
&bundle.user.token,
&mut bundle.user.limits,
&mut bundle.instance.limits,
)
.await
.unwrap()
bundle.guild.channels(&mut bundle.user).await.unwrap()
);
common::teardown(bundle).await;
}