twitch_api 0.8.0

Library for talking with the new Twitch API aka. "Helix", EventSub and more!
Documentation
//! Create Clip using Broadcaster ID (one only)
//! [`create-clip`](https://dev.twitch.tv/docs/api/reference/#create-clip)
//!
//! # Accessing the endpoint
//!
//! ## Request: [CreateClipRequest]
//!
//! To use this endpoint, construct a [`CreateClipRequest`] with the [`CreateClipRequest::broadcaster_id()`] method.
//!
//! ```rust
//! use twitch_api::helix::clips::create_clip;
//! let request = create_clip::CreateClipRequest::broadcaster_id("1234");
//! ```
//!
//! ## Response: [CreatedClip]
//!
//! Send the request to receive the response with [`HelixClient::req_post()`](helix::HelixClient::req_post).
//!
//! ```rust, no_run
//! use twitch_api::helix::{self, clips::{self, create_clip}};
//! # use twitch_api::client;
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
//! # let client: helix::HelixClient<'static, client::DummyHttpClient> = helix::HelixClient::default();
//! # let token = twitch_oauth2::AccessToken::new("validtoken".to_string());
//! # let token = twitch_oauth2::UserToken::from_existing(&client, token, None, None).await?;
//! let request = create_clip::CreateClipRequest::broadcaster_id("1234");
//! let body = helix::EmptyBody;
//! let response: clips::CreatedClip = client.req_post(request, body, &token).await?.data;
//! # Ok(())
//! # }
//! ```
//!
//! You can also get the [`http::Request`] with [`request.create_request(&token, &client_id)`](helix::RequestPost::create_request)
//! and parse the [`http::Response`] with [`CreateClipRequest::parse_response(None, &request.get_uri(), response)`](CreateClipRequest::parse_response)

use super::*;
use helix::RequestPost;

/// Query Parameters for [Create Clip](super::create_clip)
///
/// [`create-clip`](https://dev.twitch.tv/docs/api/reference/#create-clip)
#[derive(PartialEq, Deserialize, Serialize, Clone, Debug)]
#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
#[must_use]
#[non_exhaustive]
pub struct CreateClipRequest<'a> {
    /// The ID of the broadcaster whose stream you want to create a clip from.
    #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
    #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
    pub broadcaster_id: Cow<'a, types::UserIdRef>,

    /// The length of the clip in seconds. Possible values range from 5 to 60 inclusively with a precision of 0.1. The default is 30.
    #[cfg_attr(feature = "typed-builder", builder(default, setter(into)))]
    pub duration: Option<f32>,

    /// The title of the clip.
    #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
    #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
    pub title: Option<Cow<'a, str>>,
}

impl<'a> CreateClipRequest<'a> {
    /// Create a new [`CreateClipRequest`] with the given broadcaster_id
    pub fn broadcaster_id(broadcaster_id: impl types::IntoCow<'a, types::UserIdRef> + 'a) -> Self {
        Self {
            broadcaster_id: broadcaster_id.into_cow(),
            duration: None,
            title: None,
        }
    }

    /// Sets the `duration` parameter
    pub fn duration(mut self, duration: f32) -> Self {
        self.duration = Some(duration);
        self
    }

    /// Sets the `title` parameter
    pub fn title(mut self, title: impl Into<Cow<'a, str>>) -> Self {
        self.title = Some(title.into());
        self
    }
}

/// Alias for [super::CreatedClip]
pub type CreatedClip = super::CreatedClip;

impl Request for CreateClipRequest<'_> {
    type PaginationData = ();
    type Response = CreatedClip;

    const PATH: &'static str = "clips";
    #[cfg(feature = "twitch_oauth2")]
    const SCOPE: twitch_oauth2::Validator =
        twitch_oauth2::validator![twitch_oauth2::Scope::ClipsEdit];
}

impl RequestPost for CreateClipRequest<'_> {
    type Body = helix::EmptyBody;

    fn parse_inner_response(
        request: Option<Self>,
        uri: &http::Uri,
        response: &str,
        status: http::StatusCode,
    ) -> Result<helix::Response<Self, <Self as Request>::Response>, helix::HelixRequestPostError>
    where
        Self: Sized,
    {
        helix::parse_single_return(request, uri, response, status)
    }
}

#[cfg(test)]
#[test]
fn test_request() {
    use helix::*;
    let req = CreateClipRequest::broadcaster_id("44322889");

    let data = br#"
    {
        "data":
        [{
           "id": "FiveWordsForClipSlug",
           "edit_url": "http://clips.twitch.tv/FiveWordsForClipSlug/edit"
        }]
     }
    "#
    .to_vec();

    let http_response = http::Response::builder().body(data).unwrap();

    let uri = req.get_uri().unwrap();

    assert_eq!(
        uri.to_string(),
        "https://api.twitch.tv/helix/clips?broadcaster_id=44322889"
    );

    dbg!(CreateClipRequest::parse_response(Some(req), &uri, http_response).unwrap());
}