From bf800ea6848728f2a68a8aa91a060c5b1a67564c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emil=20Gardstr=C3=B6m?= Date: Fri, 2 Sep 2022 14:12:51 +0200 Subject: [PATCH] disable more --- src/helix/client.rs | 194 +++++------ src/helix/client/client_ext.rs | 430 +++++++++++------------ src/helix/mod.rs | 9 +- src/helix/request.rs | 602 ++++++++++++++++----------------- src/helix/response.rs | 104 +++--- 5 files changed, 670 insertions(+), 669 deletions(-) diff --git a/src/helix/client.rs b/src/helix/client.rs index 5a8b670767..8652677964 100644 --- a/src/helix/client.rs +++ b/src/helix/client.rs @@ -124,104 +124,104 @@ impl<'a, C: crate::HttpClient<'a>> HelixClient<'a, C> { ::parse_response(Some(request), &uri, response).map_err(Into::into) } - /// Request on a valid [`RequestPost`] endpoint - pub async fn req_post( - &'a self, - request: R, - body: B, - token: &T, - ) -> Result, ClientRequestError<>::Error>> - where - R: Request + Request + RequestPost, - B: HelixRequestBody, - D: serde::de::DeserializeOwned + PartialEq, - T: TwitchToken + ?Sized, - { - let req = - request.create_request(body, token.token().secret(), token.client_id().as_str())?; - let uri = req.uri().clone(); - let response = self - .client - .req(req) - .await - .map_err(ClientRequestError::RequestError)? - .into_response_vec() - .await?; - ::parse_response(Some(request), &uri, response).map_err(Into::into) - } + // /// Request on a valid [`RequestPost`] endpoint + // pub async fn req_post( + // &'a self, + // request: R, + // body: B, + // token: &T, + // ) -> Result, ClientRequestError<>::Error>> + // where + // R: Request + Request + RequestPost, + // B: HelixRequestBody, + // D: serde::de::DeserializeOwned + PartialEq, + // T: TwitchToken + ?Sized, + // { + // let req = + // request.create_request(body, token.token().secret(), token.client_id().as_str())?; + // let uri = req.uri().clone(); + // let response = self + // .client + // .req(req) + // .await + // .map_err(ClientRequestError::RequestError)? + // .into_response_vec() + // .await?; + // ::parse_response(Some(request), &uri, response).map_err(Into::into) + // } - /// Request on a valid [`RequestPatch`] endpoint - pub async fn req_patch( - &'a self, - request: R, - body: B, - token: &T, - ) -> Result, ClientRequestError<>::Error>> - where - R: Request + Request + RequestPatch, - B: HelixRequestBody, - D: serde::de::DeserializeOwned + PartialEq, - T: TwitchToken + ?Sized, - { - let req = - request.create_request(body, token.token().secret(), token.client_id().as_str())?; - let uri = req.uri().clone(); - let response = self - .client - .req(req) - .await - .map_err(ClientRequestError::RequestError)? - .into_response_vec() - .await?; - ::parse_response(Some(request), &uri, response).map_err(Into::into) - } + // /// Request on a valid [`RequestPatch`] endpoint + // pub async fn req_patch( + // &'a self, + // request: R, + // body: B, + // token: &T, + // ) -> Result, ClientRequestError<>::Error>> + // where + // R: Request + Request + RequestPatch, + // B: HelixRequestBody, + // D: serde::de::DeserializeOwned + PartialEq, + // T: TwitchToken + ?Sized, + // { + // let req = + // request.create_request(body, token.token().secret(), token.client_id().as_str())?; + // let uri = req.uri().clone(); + // let response = self + // .client + // .req(req) + // .await + // .map_err(ClientRequestError::RequestError)? + // .into_response_vec() + // .await?; + // ::parse_response(Some(request), &uri, response).map_err(Into::into) + // } - /// Request on a valid [`RequestDelete`] endpoint - pub async fn req_delete( - &'a self, - request: R, - token: &T, - ) -> Result, ClientRequestError<>::Error>> - where - R: Request + Request + RequestDelete, - D: serde::de::DeserializeOwned + PartialEq, - T: TwitchToken + ?Sized, - { - let req = request.create_request(token.token().secret(), token.client_id().as_str())?; - let uri = req.uri().clone(); - let response = self - .client - .req(req) - .await - .map_err(ClientRequestError::RequestError)? - .into_response_vec() - .await?; - ::parse_response(Some(request), &uri, response).map_err(Into::into) - } + // /// Request on a valid [`RequestDelete`] endpoint + // pub async fn req_delete( + // &'a self, + // request: R, + // token: &T, + // ) -> Result, ClientRequestError<>::Error>> + // where + // R: Request + Request + RequestDelete, + // D: serde::de::DeserializeOwned + PartialEq, + // T: TwitchToken + ?Sized, + // { + // let req = request.create_request(token.token().secret(), token.client_id().as_str())?; + // let uri = req.uri().clone(); + // let response = self + // .client + // .req(req) + // .await + // .map_err(ClientRequestError::RequestError)? + // .into_response_vec() + // .await?; + // ::parse_response(Some(request), &uri, response).map_err(Into::into) + // } - /// Request on a valid [`RequestPut`] endpoint - pub async fn req_put( - &'a self, - request: R, - body: B, - token: &T, - ) -> Result, ClientRequestError<>::Error>> - where - R: Request + Request + RequestPut, - B: HelixRequestBody, - D: serde::de::DeserializeOwned + PartialEq, - T: TwitchToken + ?Sized, - { - let req = - request.create_request(body, token.token().secret(), token.client_id().as_str())?; - let uri = req.uri().clone(); - let response = self - .client - .req(req) - .await - .map_err(ClientRequestError::RequestError)? - .into_response_vec() - .await?; - ::parse_response(Some(request), &uri, response).map_err(Into::into) - } + // /// Request on a valid [`RequestPut`] endpoint + // pub async fn req_put( + // &'a self, + // request: R, + // body: B, + // token: &T, + // ) -> Result, ClientRequestError<>::Error>> + // where + // R: Request + Request + RequestPut, + // B: HelixRequestBody, + // D: serde::de::DeserializeOwned + PartialEq, + // T: TwitchToken + ?Sized, + // { + // let req = + // request.create_request(body, token.token().secret(), token.client_id().as_str())?; + // let uri = req.uri().clone(); + // let response = self + // .client + // .req(req) + // .await + // .map_err(ClientRequestError::RequestError)? + // .into_response_vec() + // .await?; + // ::parse_response(Some(request), &uri, response).map_err(Into::into) + // } } diff --git a/src/helix/client/client_ext.rs b/src/helix/client/client_ext.rs index 9107682016..be927dc39d 100644 --- a/src/helix/client/client_ext.rs +++ b/src/helix/client/client_ext.rs @@ -8,44 +8,44 @@ type ClientError<'a, C> = ClientRequestError<>::Error // TODO: Consider moving these into the specific modules where the request is defined. Preferably backed by a macro -impl<'a, C: crate::HttpClient<'a> + Sync> HelixClient<'a, C> { - /// Get [User](helix::users::User) from user login - pub async fn get_user_from_login( - &'a self, - login: impl Into, - token: &T, - ) -> Result, ClientError<'a, C>> - where - T: TwitchToken + ?Sized, - { - self.req_get( - helix::users::GetUsersRequest::builder() - .login(vec![login.into()]) - .build(), - token, - ) - .await - .map(|response| response.first()) - } - - /// Get [User](helix::users::User) from user id - pub async fn get_user_from_id( - &'a self, - id: impl Into, - token: &T, - ) -> Result, ClientError<'a, C>> - where - T: TwitchToken + ?Sized, - { - self.req_get( - helix::users::GetUsersRequest::builder() - .id(vec![id.into()]) - .build(), - token, - ) - .await - .map(|response| response.first()) - } +// impl<'a, C: crate::HttpClient<'a> + Sync> HelixClient<'a, C> { + // /// Get [User](helix::users::User) from user login + // pub async fn get_user_from_login( + // &'a self, + // login: impl Into, + // token: &T, + // ) -> Result, ClientError<'a, C>> + // where + // T: TwitchToken + ?Sized, + // { + // self.req_get( + // helix::users::GetUsersRequest::builder() + // .login(vec![login.into()]) + // .build(), + // token, + // ) + // .await + // .map(|response| response.first()) + // } + + // /// Get [User](helix::users::User) from user id + // pub async fn get_user_from_id( + // &'a self, + // id: impl Into, + // token: &T, + // ) -> Result, ClientError<'a, C>> + // where + // T: TwitchToken + ?Sized, + // { + // self.req_get( + // helix::users::GetUsersRequest::builder() + // .id(vec![id.into()]) + // .build(), + // token, + // ) + // .await + // .map(|response| response.first()) + // } // /// Get [ChannelInformation](helix::channels::ChannelInformation) from a broadcasters login // pub async fn get_channel_from_login( @@ -576,180 +576,180 @@ impl<'a, C: crate::HttpClient<'a> + Sync> HelixClient<'a, C> { // .build(); // Ok(self.req_get(req, token).await?.data) // } -} - -/// Make a paginate-able request into a stream -/// -/// # Examples -/// -/// ```rust, no_run -/// # #[tokio::main] -/// # async fn main() -> Result<(), Box> { -/// # let client: helix::HelixClient<'static, twitch_api::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?; -/// use twitch_api::helix; -/// use futures::TryStreamExt; -/// -/// let req = helix::moderation::GetModeratorsRequest::builder() -/// .broadcaster_id("1234") -/// .build(); -/// -/// helix::make_stream(req, &token, &client, std::collections::VecDeque::from).try_collect::>().await? -/// # ; -/// # Ok(()) -/// # } -/// ``` -pub fn make_stream< - 'a, - C: crate::HttpClient<'a> + Send + Sync, - T: TwitchToken + ?Sized + Send + Sync, - // FIXME: Why does this have to be clone and debug? - Req: super::Request - + super::RequestGet - + super::Paginated - + Clone - + std::fmt::Debug - + Send - + Sync - + 'a, - // FIXME: this 'a seems suspicious - Item: Send + 'a, ->( - req: Req, - token: &'a T, - client: &'a super::HelixClient<'a, C>, - fun: impl Fn(::Response) -> std::collections::VecDeque - + Send - + Sync - + Copy - + 'static, -) -> std::pin::Pin>> + 'a + Send>> -where - // FIXME: This clone is bad. I want to be able to return the data, but not in a way that limits the response to be Default - // I also want to keep allocations low, so std::mem::take is perfect, but that makes get_next not work optimally. - ::Response: Send + Sync + std::fmt::Debug + Clone, -{ - use futures::StreamExt; - enum StateMode { - /// A request needs to be done. - Req(Option), - /// We have made a request, now working through the data - Cont( - super::Response::Response>, - std::collections::VecDeque, - ), - Next(Option::Response>>), - /// The operation failed, allowing no further processing - Failed, - } - - impl StateMode { - fn take_initial(&mut self) -> Req { - match self { - StateMode::Req(ref mut r) if r.is_some() => std::mem::take(r).expect("oops"), - _ => todo!("hmmm"), - } - } - - fn take_next(&mut self) -> super::Response::Response> { - match self { - StateMode::Next(ref mut r) if r.is_some() => std::mem::take(r).expect("oops"), - _ => todo!("hmmm"), - } - } - } - - struct State< - 'a, - C: crate::HttpClient<'a>, - T: TwitchToken + ?Sized, - Req: super::Request + super::RequestGet, - Item, - > { - mode: StateMode, - client: &'a HelixClient<'a, C>, - token: &'a T, - } - - impl< - 'a, - C: crate::HttpClient<'a>, - T: TwitchToken + ?Sized, - Req: super::Request + super::RequestGet + super::Paginated, - Item, - > State<'a, C, T, Req, Item> - { - /// Process a request, with a given deq - fn process( - mut self, - r: super::Response::Response>, - d: std::collections::VecDeque, - ) -> Self { - self.mode = StateMode::Cont(r, d); - self - } - - fn failed(mut self) -> Self { - self.mode = StateMode::Failed; - self - } - - /// get the next - fn get_next(mut self) -> Self { - match self.mode { - StateMode::Cont(r, d) => { - assert!(d.is_empty()); - self.mode = StateMode::Next(Some(r)); - self - } - _ => panic!("oops"), - } - } - } - let statemode = StateMode::Req(Some(req)); - let state = State { - mode: statemode, - client, - token, - }; - futures::stream::unfold(state, move |mut state: State<_, _, _, _>| async move { - match state.mode { - StateMode::Req(Some(_)) => { - let req = state.mode.take_initial(); - let f = state.client.req_get(req, state.token); - let resp = match f.await { - Ok(resp) => resp, - Err(e) => return Some((Err(e), state.failed())), - }; - let mut deq = fun(resp.data.clone()); - deq.pop_front().map(|d| (Ok(d), state.process(resp, deq))) - } - StateMode::Cont(_, ref mut deq) => { - if let Some(d) = deq.pop_front() { - if deq.is_empty() { - Some((Ok(d), state.get_next())) - } else { - Some((Ok(d), state)) - } - } else { - // New request returned empty. - None - } - } - StateMode::Next(Some(_)) => { - let resp = state.mode.take_next(); - let f = resp.get_next(state.client, state.token); - let resp = match f.await { - Ok(Some(resp)) => resp, - Ok(None) => return None, - Err(e) => return Some((Err(e), state.failed())), - }; - let mut deq = fun(resp.data.clone()); - deq.pop_front().map(|d| (Ok(d), state.process(resp, deq))) - } - _ => todo!("failed to process request"), - } - }) - .boxed() -} +// } + +// /// Make a paginate-able request into a stream +// /// +// /// # Examples +// /// +// /// ```rust, no_run +// /// # #[tokio::main] +// /// # async fn main() -> Result<(), Box> { +// /// # let client: helix::HelixClient<'static, twitch_api::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?; +// /// use twitch_api::helix; +// /// use futures::TryStreamExt; +// /// +// /// let req = helix::moderation::GetModeratorsRequest::builder() +// /// .broadcaster_id("1234") +// /// .build(); +// /// +// /// helix::make_stream(req, &token, &client, std::collections::VecDeque::from).try_collect::>().await? +// /// # ; +// /// # Ok(()) +// /// # } +// /// ``` +// pub fn make_stream< +// 'a, +// C: crate::HttpClient<'a> + Send + Sync, +// T: TwitchToken + ?Sized + Send + Sync, +// // FIXME: Why does this have to be clone and debug? +// Req: super::Request +// + super::RequestGet +// + super::Paginated +// + Clone +// + std::fmt::Debug +// + Send +// + Sync +// + 'a, +// // FIXME: this 'a seems suspicious +// Item: Send + 'a, +// >( +// req: Req, +// token: &'a T, +// client: &'a super::HelixClient<'a, C>, +// fun: impl Fn(::Response) -> std::collections::VecDeque +// + Send +// + Sync +// + Copy +// + 'static, +// ) -> std::pin::Pin>> + 'a + Send>> +// where +// // FIXME: This clone is bad. I want to be able to return the data, but not in a way that limits the response to be Default +// // I also want to keep allocations low, so std::mem::take is perfect, but that makes get_next not work optimally. +// ::Response: Send + Sync + std::fmt::Debug + Clone, +// { +// use futures::StreamExt; +// enum StateMode { +// /// A request needs to be done. +// Req(Option), +// /// We have made a request, now working through the data +// Cont( +// super::Response::Response>, +// std::collections::VecDeque, +// ), +// Next(Option::Response>>), +// /// The operation failed, allowing no further processing +// Failed, +// } + +// impl StateMode { +// fn take_initial(&mut self) -> Req { +// match self { +// StateMode::Req(ref mut r) if r.is_some() => std::mem::take(r).expect("oops"), +// _ => todo!("hmmm"), +// } +// } + +// fn take_next(&mut self) -> super::Response::Response> { +// match self { +// StateMode::Next(ref mut r) if r.is_some() => std::mem::take(r).expect("oops"), +// _ => todo!("hmmm"), +// } +// } +// } + +// struct State< +// 'a, +// C: crate::HttpClient<'a>, +// T: TwitchToken + ?Sized, +// Req: super::Request + super::RequestGet, +// Item, +// > { +// mode: StateMode, +// client: &'a HelixClient<'a, C>, +// token: &'a T, +// } + +// impl< +// 'a, +// C: crate::HttpClient<'a>, +// T: TwitchToken + ?Sized, +// Req: super::Request + super::RequestGet + super::Paginated, +// Item, +// > State<'a, C, T, Req, Item> +// { +// /// Process a request, with a given deq +// fn process( +// mut self, +// r: super::Response::Response>, +// d: std::collections::VecDeque, +// ) -> Self { +// self.mode = StateMode::Cont(r, d); +// self +// } + +// fn failed(mut self) -> Self { +// self.mode = StateMode::Failed; +// self +// } + +// /// get the next +// fn get_next(mut self) -> Self { +// match self.mode { +// StateMode::Cont(r, d) => { +// assert!(d.is_empty()); +// self.mode = StateMode::Next(Some(r)); +// self +// } +// _ => panic!("oops"), +// } +// } +// } +// let statemode = StateMode::Req(Some(req)); +// let state = State { +// mode: statemode, +// client, +// token, +// }; +// futures::stream::unfold(state, move |mut state: State<_, _, _, _>| async move { +// match state.mode { +// StateMode::Req(Some(_)) => { +// let req = state.mode.take_initial(); +// let f = state.client.req_get(req, state.token); +// let resp = match f.await { +// Ok(resp) => resp, +// Err(e) => return Some((Err(e), state.failed())), +// }; +// let mut deq = fun(resp.data.clone()); +// deq.pop_front().map(|d| (Ok(d), state.process(resp, deq))) +// } +// StateMode::Cont(_, ref mut deq) => { +// if let Some(d) = deq.pop_front() { +// if deq.is_empty() { +// Some((Ok(d), state.get_next())) +// } else { +// Some((Ok(d), state)) +// } +// } else { +// // New request returned empty. +// None +// } +// } +// StateMode::Next(Some(_)) => { +// let resp = state.mode.take_next(); +// let f = resp.get_next(state.client, state.token); +// let resp = match f.await { +// Ok(Some(resp)) => resp, +// Ok(None) => return None, +// Err(e) => return Some((Err(e), state.failed())), +// }; +// let mut deq = fun(resp.data.clone()); +// deq.pop_front().map(|d| (Ok(d), state.process(resp, deq))) +// } +// _ => todo!("failed to process request"), +// } +// }) +// .boxed() +// } diff --git a/src/helix/mod.rs b/src/helix/mod.rs index 20e93e1255..d491777baf 100644 --- a/src/helix/mod.rs +++ b/src/helix/mod.rs @@ -42,9 +42,10 @@ mod endpoints; pub mod request; pub mod response; -#[cfg(feature = "client")] -#[doc(inline)] -pub use client::{client_ext::make_stream, *}; +// #[cfg(feature = "client")] +// #[doc(inline)] +// pub use client::{client_ext::make_stream, *}; +pub use client::HelixClient; pub use endpoints::*; #[cfg(feature = "client")] #[doc(inline)] @@ -55,7 +56,7 @@ pub use request::errors::{ HelixRequestPostError, HelixRequestPutError, InvalidUri, SerializeError, }; #[doc(inline)] -pub use request::{Request, RequestDelete, RequestGet, RequestPatch, RequestPost, RequestPut}; +pub use request::{Request, RequestGet}; /* RequestDelete, RequestPatch, RequestPost, RequestPut}; */ #[doc(inline)] pub use response::Response; diff --git a/src/helix/request.rs b/src/helix/request.rs index c0085e9c4b..a24add5266 100644 --- a/src/helix/request.rs +++ b/src/helix/request.rs @@ -39,326 +39,326 @@ pub trait Request: serde::Serialize { } } -/// Helix endpoint POSTs information -pub trait RequestPost: Request { - /// Body parameters - type Body: HelixRequestBody; +// /// Helix endpoint POSTs information +// pub trait RequestPost: Request { +// /// Body parameters +// type Body: HelixRequestBody; - /// Create a [`http::Request`] from this [`Request`] in your client - fn create_request( - &self, - body: Self::Body, - token: &str, - client_id: &str, - ) -> Result, CreateRequestError> { - let uri = self.get_uri()?; +// /// Create a [`http::Request`] from this [`Request`] in your client +// fn create_request( +// &self, +// body: Self::Body, +// token: &str, +// client_id: &str, +// ) -> Result, CreateRequestError> { +// let uri = self.get_uri()?; - let body = body.try_to_body()?; - //eprintln!("\n\nbody is ------------ {} ------------", body); +// let body = body.try_to_body()?; +// //eprintln!("\n\nbody is ------------ {} ------------", body); - let mut bearer = - http::HeaderValue::from_str(&format!("Bearer {}", token)).map_err(|_| { - CreateRequestError::Custom("Could not make token into headervalue".into()) - })?; - bearer.set_sensitive(true); - http::Request::builder() - .method(http::Method::POST) - .uri(uri) - .header("Client-ID", client_id) - .header("Content-Type", "application/json") - .header(http::header::AUTHORIZATION, bearer) - .body(body) - .map_err(Into::into) - } +// let mut bearer = +// http::HeaderValue::from_str(&format!("Bearer {}", token)).map_err(|_| { +// CreateRequestError::Custom("Could not make token into headervalue".into()) +// })?; +// bearer.set_sensitive(true); +// http::Request::builder() +// .method(http::Method::POST) +// .uri(uri) +// .header("Client-ID", client_id) +// .header("Content-Type", "application/json") +// .header(http::header::AUTHORIZATION, bearer) +// .body(body) +// .map_err(Into::into) +// } - /// Parse response. - /// - /// # Notes - /// - /// Pass in the request to enable [pagination](Response::get_next) if supported. - fn parse_response>( - // FIXME: Is this really needed? Its currently only used for error reporting. - request: Option, - uri: &http::Uri, - response: http::Response, - ) -> Result::Response>, HelixRequestPostError> - where - Self: Sized, - { - let response: http::Response = response.map(|b| b.into()); - let text = std::str::from_utf8(response.body().as_ref()).map_err(|e| { - HelixRequestPostError::Utf8Error(response.body().clone(), e, uri.clone()) - })?; - if let Ok(HelixRequestError { - error, - status, - message, - }) = parse_json::(text, false) - { - return Err(HelixRequestPostError::Error { - error, - status: status.try_into().unwrap_or(http::StatusCode::BAD_REQUEST), - message, - uri: uri.clone(), - body: response.body().clone(), - }); - } - ::parse_inner_response(request, uri, text, response.status()) - } +// /// Parse response. +// /// +// /// # Notes +// /// +// /// Pass in the request to enable [pagination](Response::get_next) if supported. +// fn parse_response>( +// // FIXME: Is this really needed? Its currently only used for error reporting. +// request: Option, +// uri: &http::Uri, +// response: http::Response, +// ) -> Result::Response>, HelixRequestPostError> +// where +// Self: Sized, +// { +// let response: http::Response = response.map(|b| b.into()); +// let text = std::str::from_utf8(response.body().as_ref()).map_err(|e| { +// HelixRequestPostError::Utf8Error(response.body().clone(), e, uri.clone()) +// })?; +// if let Ok(HelixRequestError { +// error, +// status, +// message, +// }) = parse_json::(text, false) +// { +// return Err(HelixRequestPostError::Error { +// error, +// status: status.try_into().unwrap_or(http::StatusCode::BAD_REQUEST), +// message, +// uri: uri.clone(), +// body: response.body().clone(), +// }); +// } +// ::parse_inner_response(request, uri, text, response.status()) +// } - /// Parse a response string into the response. - fn parse_inner_response( - request: Option, - uri: &http::Uri, - response: &str, - status: http::StatusCode, - ) -> Result::Response>, HelixRequestPostError> - where - Self: Sized, - { - let response: InnerResponse<::Response> = parse_json(response, true) - .map_err(|e| { - HelixRequestPostError::DeserializeError( - response.to_string(), - e, - uri.clone(), - status, - ) - })?; - Ok(Response { - data: response.data, - pagination: response.pagination.cursor, - request, - total: response.total, - other: None, - }) - } -} +// /// Parse a response string into the response. +// fn parse_inner_response( +// request: Option, +// uri: &http::Uri, +// response: &str, +// status: http::StatusCode, +// ) -> Result::Response>, HelixRequestPostError> +// where +// Self: Sized, +// { +// let response: InnerResponse<::Response> = parse_json(response, true) +// .map_err(|e| { +// HelixRequestPostError::DeserializeError( +// response.to_string(), +// e, +// uri.clone(), +// status, +// ) +// })?; +// Ok(Response { +// data: response.data, +// pagination: response.pagination.cursor, +// request, +// total: response.total, +// other: None, +// }) +// } +// } -/// Helix endpoint PATCHs information -pub trait RequestPatch: Request { - /// Body parameters - type Body: HelixRequestBody; +// /// Helix endpoint PATCHs information +// pub trait RequestPatch: Request { +// /// Body parameters +// type Body: HelixRequestBody; - /// Create a [`http::Request`] from this [`Request`] in your client - fn create_request( - &self, - body: Self::Body, - token: &str, - client_id: &str, - ) -> Result, CreateRequestError> { - let uri = self.get_uri()?; +// /// Create a [`http::Request`] from this [`Request`] in your client +// fn create_request( +// &self, +// body: Self::Body, +// token: &str, +// client_id: &str, +// ) -> Result, CreateRequestError> { +// let uri = self.get_uri()?; - let body = body.try_to_body()?; - // eprintln!("\n\nbody is ------------ {} ------------", body); +// let body = body.try_to_body()?; +// // eprintln!("\n\nbody is ------------ {} ------------", body); - let mut bearer = - http::HeaderValue::from_str(&format!("Bearer {}", token)).map_err(|_| { - CreateRequestError::Custom("Could not make token into headervalue".into()) - })?; - bearer.set_sensitive(true); - http::Request::builder() - .method(http::Method::PATCH) - .uri(uri) - .header("Client-ID", client_id) - .header("Content-Type", "application/json") - .header(http::header::AUTHORIZATION, bearer) - .body(body) - .map_err(Into::into) - } +// let mut bearer = +// http::HeaderValue::from_str(&format!("Bearer {}", token)).map_err(|_| { +// CreateRequestError::Custom("Could not make token into headervalue".into()) +// })?; +// bearer.set_sensitive(true); +// http::Request::builder() +// .method(http::Method::PATCH) +// .uri(uri) +// .header("Client-ID", client_id) +// .header("Content-Type", "application/json") +// .header(http::header::AUTHORIZATION, bearer) +// .body(body) +// .map_err(Into::into) +// } - /// Parse response. - /// - /// # Notes - /// - /// Pass in the request to enable [pagination](Response::get_next) if supported. - fn parse_response>( - // FIXME: Is this really needed? Its currently only used for error reporting. - request: Option, - uri: &http::Uri, - response: http::Response, - ) -> Result::Response>, HelixRequestPatchError> - where - Self: Sized, - { - let response: http::Response = response.map(|b| b.into()); - let text = std::str::from_utf8(response.body().as_ref()).map_err(|e| { - HelixRequestPatchError::Utf8Error(response.body().clone(), e, uri.clone()) - })?; - if let Ok(HelixRequestError { - error, - status, - message, - }) = parse_json::(text, false) - { - return Err(HelixRequestPatchError::Error { - error, - status: status.try_into().unwrap_or(http::StatusCode::BAD_REQUEST), - message, - uri: uri.clone(), - body: response.body().clone(), - }); - } - ::parse_inner_response(request, uri, text, response.status()) - } +// /// Parse response. +// /// +// /// # Notes +// /// +// /// Pass in the request to enable [pagination](Response::get_next) if supported. +// fn parse_response>( +// // FIXME: Is this really needed? Its currently only used for error reporting. +// request: Option, +// uri: &http::Uri, +// response: http::Response, +// ) -> Result::Response>, HelixRequestPatchError> +// where +// Self: Sized, +// { +// let response: http::Response = response.map(|b| b.into()); +// let text = std::str::from_utf8(response.body().as_ref()).map_err(|e| { +// HelixRequestPatchError::Utf8Error(response.body().clone(), e, uri.clone()) +// })?; +// if let Ok(HelixRequestError { +// error, +// status, +// message, +// }) = parse_json::(text, false) +// { +// return Err(HelixRequestPatchError::Error { +// error, +// status: status.try_into().unwrap_or(http::StatusCode::BAD_REQUEST), +// message, +// uri: uri.clone(), +// body: response.body().clone(), +// }); +// } +// ::parse_inner_response(request, uri, text, response.status()) +// } - /// Parse a response string into the response. - fn parse_inner_response( - request: Option, - uri: &http::Uri, - response: &str, - status: http::StatusCode, - ) -> Result::Response>, HelixRequestPatchError> - where - Self: Sized; -} +// /// Parse a response string into the response. +// fn parse_inner_response( +// request: Option, +// uri: &http::Uri, +// response: &str, +// status: http::StatusCode, +// ) -> Result::Response>, HelixRequestPatchError> +// where +// Self: Sized; +// } -/// Helix endpoint DELETEs information -pub trait RequestDelete: Request { - /// Create a [`http::Request`] from this [`Request`] in your client - fn create_request( - &self, - token: &str, - client_id: &str, - ) -> Result, CreateRequestError> { - let uri = self.get_uri()?; +// /// Helix endpoint DELETEs information +// pub trait RequestDelete: Request { +// /// Create a [`http::Request`] from this [`Request`] in your client +// fn create_request( +// &self, +// token: &str, +// client_id: &str, +// ) -> Result, CreateRequestError> { +// let uri = self.get_uri()?; - let mut bearer = - http::HeaderValue::from_str(&format!("Bearer {}", token)).map_err(|_| { - CreateRequestError::Custom("Could not make token into headervalue".into()) - })?; - bearer.set_sensitive(true); - http::Request::builder() - .method(http::Method::DELETE) - .uri(uri) - .header("Client-ID", client_id) - .header("Content-Type", "application/json") - .header(http::header::AUTHORIZATION, bearer) - .body(Vec::with_capacity(0).into()) - .map_err(Into::into) - } - /// Parse response. - /// - /// # Notes - /// - /// Pass in the request to enable [pagination](Response::get_next) if supported. - fn parse_response>( - // FIXME: Is this really needed? Its currently only used for error reporting. - request: Option, - uri: &http::Uri, - response: http::Response, - ) -> Result::Response>, HelixRequestDeleteError> - where - Self: Sized, - { - let response: http::Response = response.map(|b| b.into()); - let text = std::str::from_utf8(response.body().as_ref()).map_err(|e| { - HelixRequestDeleteError::Utf8Error(response.body().clone(), e, uri.clone()) - })?; - if let Ok(HelixRequestError { - error, - status, - message, - }) = parse_json::(text, false) - { - return Err(HelixRequestDeleteError::Error { - error, - status: status.try_into().unwrap_or(http::StatusCode::BAD_REQUEST), - message, - uri: uri.clone(), - body: response.body().clone(), - }); - } - ::parse_inner_response(request, uri, text, response.status()) - } - /// Parse a response string into the response. - fn parse_inner_response( - request: Option, - uri: &http::Uri, - response: &str, - status: http::StatusCode, - ) -> Result::Response>, HelixRequestDeleteError> - where - Self: Sized; -} +// let mut bearer = +// http::HeaderValue::from_str(&format!("Bearer {}", token)).map_err(|_| { +// CreateRequestError::Custom("Could not make token into headervalue".into()) +// })?; +// bearer.set_sensitive(true); +// http::Request::builder() +// .method(http::Method::DELETE) +// .uri(uri) +// .header("Client-ID", client_id) +// .header("Content-Type", "application/json") +// .header(http::header::AUTHORIZATION, bearer) +// .body(Vec::with_capacity(0).into()) +// .map_err(Into::into) +// } +// /// Parse response. +// /// +// /// # Notes +// /// +// /// Pass in the request to enable [pagination](Response::get_next) if supported. +// fn parse_response>( +// // FIXME: Is this really needed? Its currently only used for error reporting. +// request: Option, +// uri: &http::Uri, +// response: http::Response, +// ) -> Result::Response>, HelixRequestDeleteError> +// where +// Self: Sized, +// { +// let response: http::Response = response.map(|b| b.into()); +// let text = std::str::from_utf8(response.body().as_ref()).map_err(|e| { +// HelixRequestDeleteError::Utf8Error(response.body().clone(), e, uri.clone()) +// })?; +// if let Ok(HelixRequestError { +// error, +// status, +// message, +// }) = parse_json::(text, false) +// { +// return Err(HelixRequestDeleteError::Error { +// error, +// status: status.try_into().unwrap_or(http::StatusCode::BAD_REQUEST), +// message, +// uri: uri.clone(), +// body: response.body().clone(), +// }); +// } +// ::parse_inner_response(request, uri, text, response.status()) +// } +// /// Parse a response string into the response. +// fn parse_inner_response( +// request: Option, +// uri: &http::Uri, +// response: &str, +// status: http::StatusCode, +// ) -> Result::Response>, HelixRequestDeleteError> +// where +// Self: Sized; +// } -/// Helix endpoint PUTs information -pub trait RequestPut: Request { - /// Body parameters - type Body: HelixRequestBody; +// /// Helix endpoint PUTs information +// pub trait RequestPut: Request { +// /// Body parameters +// type Body: HelixRequestBody; - /// Create a [`http::Request`] from this [`Request`] in your client - fn create_request( - &self, - body: Self::Body, - token: &str, - client_id: &str, - ) -> Result, CreateRequestError> { - let uri = self.get_uri()?; +// /// Create a [`http::Request`] from this [`Request`] in your client +// fn create_request( +// &self, +// body: Self::Body, +// token: &str, +// client_id: &str, +// ) -> Result, CreateRequestError> { +// let uri = self.get_uri()?; - let body = body.try_to_body()?; - // eprintln!("\n\nbody is ------------ {} ------------", body); +// let body = body.try_to_body()?; +// // eprintln!("\n\nbody is ------------ {} ------------", body); - let mut bearer = - http::HeaderValue::from_str(&format!("Bearer {}", token)).map_err(|_| { - CreateRequestError::Custom("Could not make token into headervalue".into()) - })?; - bearer.set_sensitive(true); - http::Request::builder() - .method(http::Method::PUT) - .uri(uri) - .header("Client-ID", client_id) - .header("Content-Type", "application/json") - .header(http::header::AUTHORIZATION, bearer) - .body(body) - .map_err(Into::into) - } +// let mut bearer = +// http::HeaderValue::from_str(&format!("Bearer {}", token)).map_err(|_| { +// CreateRequestError::Custom("Could not make token into headervalue".into()) +// })?; +// bearer.set_sensitive(true); +// http::Request::builder() +// .method(http::Method::PUT) +// .uri(uri) +// .header("Client-ID", client_id) +// .header("Content-Type", "application/json") +// .header(http::header::AUTHORIZATION, bearer) +// .body(body) +// .map_err(Into::into) +// } - /// Parse response. - /// - /// # Notes - /// - /// Pass in the request to enable [pagination](Response::get_next) if supported. - fn parse_response>( - // FIXME: Is this really needed? Its currently only used for error reporting. - request: Option, - uri: &http::Uri, - response: http::Response, - ) -> Result::Response>, HelixRequestPutError> - where - Self: Sized, - { - let response: http::Response = response.map(|b| b.into()); - let text = std::str::from_utf8(response.body().as_ref()).map_err(|e| { - HelixRequestPutError::Utf8Error(response.body().clone(), e, uri.clone()) - })?; - if let Ok(HelixRequestError { - error, - status, - message, - }) = parse_json::(text, false) - { - return Err(HelixRequestPutError::Error { - error, - status: status.try_into().unwrap_or(http::StatusCode::BAD_REQUEST), - message, - uri: uri.clone(), - body: response.body().clone(), - }); - } - ::parse_inner_response(request, uri, text, response.status()) - } +// /// Parse response. +// /// +// /// # Notes +// /// +// /// Pass in the request to enable [pagination](Response::get_next) if supported. +// fn parse_response>( +// // FIXME: Is this really needed? Its currently only used for error reporting. +// request: Option, +// uri: &http::Uri, +// response: http::Response, +// ) -> Result::Response>, HelixRequestPutError> +// where +// Self: Sized, +// { +// let response: http::Response = response.map(|b| b.into()); +// let text = std::str::from_utf8(response.body().as_ref()).map_err(|e| { +// HelixRequestPutError::Utf8Error(response.body().clone(), e, uri.clone()) +// })?; +// if let Ok(HelixRequestError { +// error, +// status, +// message, +// }) = parse_json::(text, false) +// { +// return Err(HelixRequestPutError::Error { +// error, +// status: status.try_into().unwrap_or(http::StatusCode::BAD_REQUEST), +// message, +// uri: uri.clone(), +// body: response.body().clone(), +// }); +// } +// ::parse_inner_response(request, uri, text, response.status()) +// } - /// Parse a response string into the response. - fn parse_inner_response( - request: Option, - uri: &http::Uri, - response: &str, - status: http::StatusCode, - ) -> Result::Response>, HelixRequestPutError> - where - Self: Sized; -} +// /// Parse a response string into the response. +// fn parse_inner_response( +// request: Option, +// uri: &http::Uri, +// response: &str, +// status: http::StatusCode, +// ) -> Result::Response>, HelixRequestPutError> +// where +// Self: Sized; +// } /// Helix endpoint GETs information pub trait RequestGet: Request { diff --git a/src/helix/response.rs b/src/helix/response.rs index 6cbf40e243..2536cbd620 100644 --- a/src/helix/response.rs +++ b/src/helix/response.rs @@ -53,61 +53,61 @@ where } } -impl Response -where - R: Request, - D: IntoIterator + PartialEq + serde::de::DeserializeOwned, -{ - /// Get first result of this response. - pub fn first(self) -> Option { self.data.into_iter().next() } -} - -// impl CustomResponse<'_, R, D> +// impl Response // where // R: Request, -// D: IntoIterator, +// D: IntoIterator + PartialEq + serde::de::DeserializeOwned, // { // /// Get first result of this response. -// pub fn first(self) -> Option { self.data().into_iter().next() } +// pub fn first(self) -> Option { self.data.into_iter().next() } // } -#[cfg(feature = "client")] -impl Response -where - R: Request + Clone + super::Paginated + super::RequestGet + std::fmt::Debug, - D: serde::de::DeserializeOwned + std::fmt::Debug + PartialEq, -{ - /// Get the next page in the responses. - pub async fn get_next<'a, C: crate::HttpClient<'a>>( - self, - client: &'a super::HelixClient<'a, C>, - token: &(impl super::TwitchToken + ?Sized), - ) -> Result< - Option>, - super::ClientRequestError<>::Error>, - > { - if let Some(mut req) = self.request.clone() { - if self.pagination.is_some() { - req.set_pagination(self.pagination); - let res = client.req_get(req, token).await.map(Some); - if let Ok(Some(r)) = res { - // FIXME: Workaround for https://github.com/twitchdev/issues/issues/18 - if r.data == self.data { - Ok(None) - } else { - Ok(Some(r)) - } - } else { - res - } - } else { - Ok(None) - } - } else { - // TODO: Make into proper error - Err(super::ClientRequestError::Custom( - "no source request attached".into(), - )) - } - } -} +// // impl CustomResponse<'_, R, D> +// // where +// // R: Request, +// // D: IntoIterator, +// // { +// // /// Get first result of this response. +// // pub fn first(self) -> Option { self.data().into_iter().next() } +// // } + +// #[cfg(feature = "client")] +// impl Response +// where +// R: Request + Clone + super::Paginated + super::RequestGet + std::fmt::Debug, +// D: serde::de::DeserializeOwned + std::fmt::Debug + PartialEq, +// { +// /// Get the next page in the responses. +// pub async fn get_next<'a, C: crate::HttpClient<'a>>( +// self, +// client: &'a super::HelixClient<'a, C>, +// token: &(impl super::TwitchToken + ?Sized), +// ) -> Result< +// Option>, +// super::ClientRequestError<>::Error>, +// > { +// if let Some(mut req) = self.request.clone() { +// if self.pagination.is_some() { +// req.set_pagination(self.pagination); +// let res = client.req_get(req, token).await.map(Some); +// if let Ok(Some(r)) = res { +// // FIXME: Workaround for https://github.com/twitchdev/issues/issues/18 +// if r.data == self.data { +// Ok(None) +// } else { +// Ok(Some(r)) +// } +// } else { +// res +// } +// } else { +// Ok(None) +// } +// } else { +// // TODO: Make into proper error +// Err(super::ClientRequestError::Custom( +// "no source request attached".into(), +// )) +// } +// } +// }