use std::marker::PhantomData;
use super::*;
use helix::RequestPost;
#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug, Default)]
#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
#[must_use]
#[non_exhaustive]
pub struct CreatePredictionRequest<'a> {
#[cfg_attr(feature = "typed-builder", builder(default))]
#[serde(skip)]
_marker: PhantomData<&'a ()>,
}
impl CreatePredictionRequest<'_> {
pub fn new() -> Self { Self::default() }
}
#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug)]
#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
#[non_exhaustive]
pub struct CreatePredictionBody<'a> {
#[cfg_attr(feature = "typed-builder", builder(setter(into)))]
#[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
pub broadcaster_id: Cow<'a, types::UserIdRef>,
#[cfg_attr(feature = "typed-builder", builder(setter(into)))]
#[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
pub title: Cow<'a, str>,
#[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
pub outcomes: Cow<'a, [NewPredictionOutcome<'a>]>,
pub prediction_window: i64,
}
impl<'a> CreatePredictionBody<'a> {
pub fn new(
broadcaster_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
title: impl Into<Cow<'a, str>>,
outcomes: &'a [NewPredictionOutcome<'a>],
prediction_window: i64,
) -> Self {
Self {
broadcaster_id: broadcaster_id.into_cow(),
title: title.into(),
outcomes: outcomes.into(),
prediction_window,
}
}
}
impl helix::private::SealedSerialize for CreatePredictionBody<'_> {}
#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug)]
#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
#[non_exhaustive]
pub struct NewPredictionOutcome<'a> {
#[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
pub title: Cow<'a, str>,
}
impl<'a> NewPredictionOutcome<'a> {
pub fn new(title: impl Into<Cow<'a, str>>) -> Self {
Self {
title: title.into(),
}
}
}
pub type CreatePredictionResponse = super::Prediction;
impl Request for CreatePredictionRequest<'_> {
type Response = CreatePredictionResponse;
const PATH: &'static str = "predictions";
#[cfg(feature = "twitch_oauth2")]
const SCOPE: twitch_oauth2::Validator =
twitch_oauth2::validator![twitch_oauth2::Scope::ChannelManagePredictions];
}
impl<'a> RequestPost for CreatePredictionRequest<'a> {
type Body = CreatePredictionBody<'a>;
fn parse_inner_response(
request: Option<Self>,
uri: &http::Uri,
response_str: &str,
status: http::StatusCode,
) -> Result<helix::Response<Self, Self::Response>, helix::HelixRequestPostError>
where
Self: Sized,
{
let response: helix::InnerResponse<Vec<Self::Response>> =
helix::parse_json(response_str, true).map_err(|e| {
helix::HelixRequestPostError::DeserializeError(
response_str.to_string(),
e,
uri.clone(),
status,
)
})?;
let data = response.data.into_iter().next().ok_or_else(|| {
helix::HelixRequestPostError::InvalidResponse {
reason: "response included no data",
response: response_str.to_string(),
status,
uri: uri.clone(),
}
})?;
Ok(helix::Response {
data,
pagination: response.pagination.cursor,
request,
total: None,
other: None,
})
}
}
#[cfg(test)]
#[test]
fn test_request() {
use helix::*;
let req = CreatePredictionRequest::new();
let outcomes = &[
NewPredictionOutcome::new("Yes, give it time."),
NewPredictionOutcome::new("Definitely not."),
];
let body = CreatePredictionBody::new("141981764", "Any leeks in the stream?", outcomes, 120);
assert_eq!(
std::str::from_utf8(&body.try_to_body().unwrap()).unwrap(),
r#"{"broadcaster_id":"141981764","title":"Any leeks in the stream?","outcomes":[{"title":"Yes, give it time."},{"title":"Definitely not."}],"prediction_window":120}"#
);
dbg!(req.create_request(body, "token", "clientid").unwrap());
let data = br##"
{
"data": [
{
"id": "bc637af0-7766-4525-9308-4112f4cbf178",
"broadcaster_id": "141981764",
"broadcaster_name": "TwitchDev",
"broadcaster_login": "twitchdev",
"title": "Any leeks in the stream?",
"winning_outcome_id": null,
"outcomes": [
{
"id": "73085848-a94d-4040-9d21-2cb7a89374b7",
"title": "Yes, give it time.",
"users": 0,
"channel_points": 0,
"top_predictors": null,
"color": "BLUE"
},
{
"id": "906b70ba-1f12-47ea-9e95-e5f93d20e9cc",
"title": "Definitely not.",
"users": 0,
"channel_points": 0,
"top_predictors": null,
"color": "PINK"
}
],
"prediction_window": 120,
"status": "ACTIVE",
"created_at": "2021-04-28T17:11:22.595914172Z",
"ended_at": null,
"locked_at": null
}
]
}
"##
.to_vec();
let http_response = http::Response::builder().status(200).body(data).unwrap();
let uri = req.get_uri().unwrap();
assert_eq!(uri.to_string(), "https://api.twitch.tv/helix/predictions?");
dbg!(CreatePredictionRequest::parse_response(Some(req), &uri, http_response).unwrap());
}