Merge pull request #26 from dscottboggs/fix/clone-as-into

Fix/clone as into
This commit is contained in:
Scott Boggs 2022-12-28 16:31:15 -05:00 committed by GitHub
commit 520247fade
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 71 additions and 57 deletions

View File

@ -25,6 +25,6 @@ async fn main() -> Result<()> {
fn main() { fn main() {
println!( println!(
"examples require the `toml` feature, run this command for this example:\n\ncargo run \ "examples require the `toml` feature, run this command for this example:\n\ncargo run \
--example print_your_profile --features toml\n" --example follows_me --features toml\n"
); );
} }

32
examples/get_statuses.rs Normal file
View File

@ -0,0 +1,32 @@
#![cfg_attr(not(feature = "toml"), allow(dead_code))]
#![cfg_attr(not(feature = "toml"), allow(unused_imports))]
mod register;
use mastodon_async::Result;
#[cfg(feature = "toml")]
#[tokio::main]
async fn main() -> Result<()> {
use futures_util::StreamExt;
use mastodon_async::StatusesRequest;
let mut filters = StatusesRequest::new();
filters.limit(3);
let mastodon = register::get_mastodon_data().await?;
let you = mastodon.verify_credentials().await?;
mastodon
.statuses(&you.id, filters)
.await?
.items_iter()
.for_each(|status| async move { println!("{status:?}") })
.await;
Ok(())
}
#[cfg(not(feature = "toml"))]
fn main() {
println!(
"examples require the `toml` feature, run this command for this example:\n\ncargo run \
--example get_statuses --features toml\n"
);
}

View File

@ -12,7 +12,7 @@ async fn main() -> Result<()> {
.status(register::read_line( .status(register::read_line(
"Enter a status to post privately (enter to send): ", "Enter a status to post privately (enter to send): ",
)?) )?)
.visibility(Visibility::Private) .visibility(Visibility::Unlisted)
.language(Language::Eng) .language(Language::Eng)
.build()?; .build()?;

View File

@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize};
/// tokio_test::block_on(async { /// tokio_test::block_on(async {
/// let data = Data::default(); /// let data = Data::default();
/// let client = Mastodon::from(data); /// let client = Mastodon::from(data);
/// let statuses = client.statuses("user-id", None).await.unwrap().items_iter(); /// let statuses = client.statuses("user-id", Default::default()).await.unwrap().items_iter();
/// statuses.for_each(|status| async move { /// statuses.for_each(|status| async move {
/// // Do something with the status /// // Do something with the status
/// }).await; /// }).await;

View File

@ -94,11 +94,7 @@ pub use mastodon::{Mastodon, MastodonUnauthenticated};
// pub use mastodon_client::{MastodonClient, MastodonUnauthenticated}; // pub use mastodon_client::{MastodonClient, MastodonUnauthenticated};
pub use registration::Registration; pub use registration::Registration;
pub use requests::{ pub use requests::{
AddFilterRequest, AddFilterRequest, AddPushRequest, StatusesRequest, UpdateCredsRequest, UpdatePushRequest,
AddPushRequest,
StatusesRequest,
UpdateCredsRequest,
UpdatePushRequest,
}; };
pub use status_builder::{NewStatus, StatusBuilder, Visibility}; pub use status_builder::{NewStatus, StatusBuilder, Visibility};

View File

@ -225,7 +225,7 @@ impl Mastodon {
/// tokio_test::block_on(async { /// tokio_test::block_on(async {
/// let data = Data::default(); /// let data = Data::default();
/// let client = Mastodon::from(data); /// let client = Mastodon::from(data);
/// let statuses = client.statuses("user-id", None).await.unwrap(); /// let statuses = client.statuses("user-id", Default::default()).await.unwrap();
/// }); /// });
/// ``` /// ```
/// ///
@ -239,16 +239,15 @@ impl Mastodon {
/// let statuses = client.statuses("user-id", request).await.unwrap(); /// let statuses = client.statuses("user-id", request).await.unwrap();
/// }); /// });
/// ``` /// ```
pub async fn statuses<'a, 'b: 'a, S>(&'b self, id: &'b str, request: S) -> Result<Page<Status>> pub async fn statuses<'a, 'b: 'a>(
where &'b self,
S: Into<Option<StatusesRequest<'a>>>, id: &'b str,
{ request: StatusesRequest<'a>,
) -> Result<Page<Status>> {
let call_id = Uuid::new_v4(); let call_id = Uuid::new_v4();
let mut url = format!("{}/api/v1/accounts/{}/statuses", self.data.base, id); let mut url = format!("{}/api/v1/accounts/{}/statuses", self.data.base, id);
if let Some(request) = request.into() { url += request.to_query_string()?.as_str();
url = format!("{}{}", url, request.to_querystring()?);
}
debug!(url = url, method = stringify!($method), call_id = as_debug!(call_id); "making API request"); debug!(url = url, method = stringify!($method), call_id = as_debug!(call_id); "making API request");
let response = self.client.get(&url).send().await?; let response = self.client.get(&url).send().await?;

View File

@ -1,9 +1,6 @@
use super::{Mastodon, Result}; use super::{Mastodon, Result};
use crate::{ use crate::{
entities::itemsiter::ItemsIter, entities::itemsiter::ItemsIter, format_err, helpers::read_response::read_response, Error,
format_err,
helpers::read_response::read_response,
Error,
}; };
use futures::Stream; use futures::Stream;
use hyper_old_types::header::{parsing, Link, RelationType}; use hyper_old_types::header::{parsing, Link, RelationType};
@ -130,10 +127,7 @@ impl<'a, T: for<'de> Deserialize<'de> + Serialize> Page<T> {
}) })
} else { } else {
let response = response.json().await?; let response = response.json().await?;
Err(Error::Api { Err(Error::Api { status, response })
status,
response,
})
} }
} }
} }

View File

@ -27,7 +27,7 @@ mod bool_qs_serialize {
/// use mastodon_async::requests::StatusesRequest; /// use mastodon_async::requests::StatusesRequest;
/// let mut request = StatusesRequest::new(); /// let mut request = StatusesRequest::new();
/// request.only_media().pinned().since_id("foo"); /// request.only_media().pinned().since_id("foo");
/// assert_eq!(&request.to_querystring().expect("Couldn't serialize qs")[..], "?only_media=1&pinned=1&since_id=foo"); /// assert_eq!(&request.to_query_string().expect("Couldn't serialize qs")[..], "?only_media=1&pinned=1&since_id=foo");
/// ``` /// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)] #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct StatusesRequest<'a> { pub struct StatusesRequest<'a> {
@ -75,8 +75,9 @@ impl<'a> StatusesRequest<'a> {
/// // Example /// // Example
/// ///
/// ``` /// ```
/// let mut request = mastodon_async::requests::StatusesRequest::new(); /// use mastodon_async::requests::StatusesRequest;
/// assert_eq!(&request.only_media().to_querystring().expect("Couldn't serialize qs"), "?only_media=1"); /// let mut request = StatusesRequest::new();
/// assert_eq!(&request.only_media().to_query_string().expect("Couldn't serialize qs"), "?only_media=1");
/// ``` /// ```
pub fn only_media(&mut self) -> &mut Self { pub fn only_media(&mut self) -> &mut Self {
self.only_media = true; self.only_media = true;
@ -88,11 +89,12 @@ impl<'a> StatusesRequest<'a> {
/// // Example /// // Example
/// ///
/// ``` /// ```
/// let mut request = mastodon_async::requests::StatusesRequest::new(); /// use mastodon_async::requests::StatusesRequest;
/// let mut request = StatusesRequest::new();
/// assert_eq!( /// assert_eq!(
/// &request /// &request
/// .exclude_replies() /// .exclude_replies()
/// .to_querystring() /// .to_query_string()
/// .expect("Couldn't serialize qs"), /// .expect("Couldn't serialize qs"),
/// "?exclude_replies=1" /// "?exclude_replies=1"
/// ); /// );
@ -107,11 +109,12 @@ impl<'a> StatusesRequest<'a> {
/// // Example /// // Example
/// ///
/// ``` /// ```
/// let mut request = mastodon_async::requests::StatusesRequest::new(); /// use mastodon_async::requests::StatusesRequest;
/// let mut request = StatusesRequest::new();
/// assert_eq!( /// assert_eq!(
/// &request /// &request
/// .pinned() /// .pinned()
/// .to_querystring() /// .to_query_string()
/// .expect("Couldn't serialize qs"), /// .expect("Couldn't serialize qs"),
/// "?pinned=1" /// "?pinned=1"
/// ); /// );
@ -126,11 +129,12 @@ impl<'a> StatusesRequest<'a> {
/// // Example /// // Example
/// ///
/// ``` /// ```
/// let mut request = mastodon_async::requests::StatusesRequest::new(); /// use mastodon_async::requests::StatusesRequest;
/// let mut request = StatusesRequest::new();
/// assert_eq!( /// assert_eq!(
/// &request /// &request
/// .max_id("foo") /// .max_id("foo")
/// .to_querystring() /// .to_query_string()
/// .expect("Couldn't serialize qs"), /// .expect("Couldn't serialize qs"),
/// "?max_id=foo" /// "?max_id=foo"
/// ); /// );
@ -145,11 +149,12 @@ impl<'a> StatusesRequest<'a> {
/// // Example /// // Example
/// ///
/// ``` /// ```
/// let mut request = mastodon_async::requests::StatusesRequest::new(); /// use mastodon_async::requests::StatusesRequest;
/// let mut request = StatusesRequest::new();
/// assert_eq!( /// assert_eq!(
/// &request /// &request
/// .since_id("foo") /// .since_id("foo")
/// .to_querystring() /// .to_query_string()
/// .expect("Couldn't serialize qs"), /// .expect("Couldn't serialize qs"),
/// "?since_id=foo" /// "?since_id=foo"
/// ); /// );
@ -164,11 +169,12 @@ impl<'a> StatusesRequest<'a> {
/// // Example /// // Example
/// ///
/// ``` /// ```
/// let mut request = mastodon_async::requests::StatusesRequest::new(); /// use mastodon_async::requests::StatusesRequest;
/// let mut request = StatusesRequest::new();
/// assert_eq!( /// assert_eq!(
/// &request /// &request
/// .limit(10) /// .limit(10)
/// .to_querystring() /// .to_query_string()
/// .expect("Couldn't serialize qs"), /// .expect("Couldn't serialize qs"),
/// "?limit=10" /// "?limit=10"
/// ); /// );
@ -183,11 +189,12 @@ impl<'a> StatusesRequest<'a> {
/// // Example /// // Example
/// ///
/// ``` /// ```
/// let mut request = mastodon_async::requests::StatusesRequest::new(); /// use mastodon_async::requests::StatusesRequest;
/// let mut request = StatusesRequest::new();
/// assert_eq!( /// assert_eq!(
/// &request /// &request
/// .min_id("foobar") /// .min_id("foobar")
/// .to_querystring() /// .to_query_string()
/// .expect("Couldn't serialize qs"), /// .expect("Couldn't serialize qs"),
/// "?min_id=foobar" /// "?min_id=foobar"
/// ); /// );
@ -197,22 +204,8 @@ impl<'a> StatusesRequest<'a> {
self self
} }
/// Turns this builder into a querystring /// Serialize into a query string
/// pub fn to_query_string(&self) -> Result<String, Error> {
/// // Example
///
/// ```
/// let mut request = mastodon_async::requests::StatusesRequest::new();
/// assert_eq!(
/// &request
/// .limit(10)
/// .pinned()
/// .to_querystring()
/// .expect("Couldn't serialize qs"),
/// "?pinned=1&limit=10"
/// );
/// ```
pub fn to_querystring(&self) -> Result<String, Error> {
Ok(format!("?{}", serde_qs::to_string(&self)?)) Ok(format!("?{}", serde_qs::to_string(&self)?))
} }
} }
@ -359,13 +352,13 @@ mod tests {
); );
} }
#[test] #[test]
fn test_to_querystring() { fn test_to_query_string() {
macro_rules! qs_test { macro_rules! qs_test {
(|$r:ident| $b:block, $expected:expr) => { (|$r:ident| $b:block, $expected:expr) => {
{ {
let mut $r = StatusesRequest::new(); let mut $r = StatusesRequest::new();
$b $b
let qs = $r.to_querystring().expect("Failed to serialize querystring"); let qs = $r.to_query_string().expect("Failed to serialize querystring");
assert_eq!(&qs, $expected); assert_eq!(&qs, $expected);
} }
} }