twitch_api/helix/endpoints/games/get_top_games.rs
1//! Gets games sorted by number of current viewers on Twitch, most popular first.
2//! [`get-top-games`](https://dev.twitch.tv/docs/api/reference#get-top-games)
3//!
4//! # Accessing the endpoint
5//!
6//! ## Request: [GetTopGamesRequest]
7//!
8//! To use this endpoint, construct a [`GetTopGamesRequest`] with the [`GetTopGamesRequest::default()`] method.
9//!
10//! ```rust
11//! use twitch_api::helix::games::get_top_games;
12//! let request = get_top_games::GetTopGamesRequest::default().first(100);
13//! ```
14//!
15//! ## Response: [Game](types::TwitchCategory)
16//!
17//! Send the request to receive the response with [`HelixClient::req_get()`](helix::HelixClient::req_get).
18//!
19//! ```rust, no_run
20//! use twitch_api::helix::{self, games::get_top_games};
21//! # use twitch_api::client;
22//! # #[tokio::main]
23//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
24//! # let client: helix::HelixClient<'static, client::DummyHttpClient> = helix::HelixClient::default();
25//! # let token = twitch_oauth2::AccessToken::new("validtoken".to_string());
26//! # let token = twitch_oauth2::UserToken::from_existing(&client, token, None, None).await?;
27//! let request = get_top_games::GetTopGamesRequest::default();
28//! let response: Vec<get_top_games::Game> = client.req_get(request, &token).await?.data;
29//! # Ok(())
30//! # }
31//! ```
32//!
33//! You can also get the [`http::Request`] with [`request.create_request(&token, &client_id)`](helix::RequestGet::create_request)
34//! and parse the [`http::Response`] with [`GetTopGamesRequest::parse_response(None, &request.get_uri(), response)`](GetTopGamesRequest::parse_response)
35
36use super::*;
37use helix::RequestGet;
38
39/// Query Parameters for [Get Top Games](super::get_games)
40///
41/// [`get-top-games`](https://dev.twitch.tv/docs/api/reference#get-top-games)
42#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug, Default)]
43#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
44#[must_use]
45#[non_exhaustive]
46pub struct GetTopGamesRequest<'a> {
47 /// Cursor for forward pagination: tells the server where to start fetching the next set of results, in a multi-page response. The cursor value specified here is from the pagination response field of a prior query.
48 #[cfg_attr(feature = "typed-builder", builder(default, setter(into)))]
49 #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
50 pub after: Option<Cow<'a, helix::CursorRef>>,
51 /// Cursor for backward pagination: tells the server where to start fetching the next set of results, in a multi-page response. The cursor value specified here is from the pagination response field of a prior query.
52 #[cfg_attr(feature = "typed-builder", builder(default, setter(into)))]
53 #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
54 pub before: Option<Cow<'a, helix::CursorRef>>,
55 /// Maximum number of objects to return. Maximum: 100. Default: 20.
56 #[cfg_attr(feature = "typed-builder", builder(default, setter(into)))]
57 pub first: Option<usize>,
58}
59
60impl GetTopGamesRequest<'_> {
61 /// Set amount of results returned per page.
62 pub const fn first(mut self, first: usize) -> Self {
63 self.first = Some(first);
64 self
65 }
66}
67
68/// Return Values for [Get Top Games](super::get_games)
69///
70/// [`get-top-games`](https://dev.twitch.tv/docs/api/reference#get-top-games)
71pub type Game = types::TwitchCategory;
72
73impl Request for GetTopGamesRequest<'_> {
74 type Response = Vec<Game>;
75
76 const PATH: &'static str = "games/top";
77 #[cfg(feature = "twitch_oauth2")]
78 const SCOPE: twitch_oauth2::Validator = twitch_oauth2::validator![];
79}
80
81impl RequestGet for GetTopGamesRequest<'_> {}
82
83impl helix::Paginated for GetTopGamesRequest<'_> {
84 fn set_pagination(&mut self, cursor: Option<helix::Cursor>) {
85 self.after = cursor.map(|c| c.into_cow())
86 }
87}
88
89#[cfg(test)]
90#[test]
91fn test_request() {
92 use helix::*;
93 let req = GetTopGamesRequest::default();
94
95 // From twitch docs
96 let data = br#"
97{
98 "data": [
99 {
100 "id": "493057",
101 "name": "PLAYERUNKNOWN'S BATTLEGROUNDS",
102 "box_art_url": "https://static-cdn.jtvnw.net/ttv-boxart/PLAYERUNKNOWN%27S%20BATTLEGROUNDS-{width}x{height}.jpg",
103 "igdb_id": "27789"
104 },
105 {
106 "id": "493057",
107 "name": "PLAYERUNKNOWN'S BATTLEGROUNDS",
108 "box_art_url": "https://static-cdn.jtvnw.net/ttv-boxart/PLAYERUNKNOWN%27S%20BATTLEGROUNDS-{width}x{height}.jpg",
109 "igdb_id": "27789"
110 }
111 ],
112 "pagination":{"cursor":"eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MjB9fQ=="}
113}
114"#
115 .to_vec();
116
117 let http_response = http::Response::builder().body(data).unwrap();
118
119 let uri = req.get_uri().unwrap();
120 assert_eq!(uri.to_string(), "https://api.twitch.tv/helix/games/top?");
121
122 dbg!(GetTopGamesRequest::parse_response(Some(req), &uri, http_response).unwrap());
123}