Skip to main content

twapi_v2/api/
get_2_spaces_id.rs

1use crate::fields::{
2    space_fields::SpaceFields, topic_fields::TopicFields, user_fields::UserFields,
3};
4use crate::responses::{errors::Errors, includes::Includes, spaces::Spaces};
5use crate::{
6    api::{Authentication, TwapiOptions, execute_twitter, make_url},
7    error::Error,
8    headers::Headers,
9};
10use itertools::Itertools;
11use reqwest::RequestBuilder;
12use serde::{Deserialize, Serialize};
13use std::collections::HashSet;
14
15const URL: &str = "/2/spaces/:id";
16
17#[derive(Serialize, Deserialize, Debug, Eq, Hash, PartialEq, Clone)]
18#[derive(Default)]
19pub enum Expansions {
20    #[serde(rename = "invited_user_ids")]
21    #[default]
22    InvitedUserIds,
23    #[serde(rename = "speaker_ids")]
24    SpeakerIds,
25    #[serde(rename = "creator_id")]
26    CreatorId,
27    #[serde(rename = "host_ids")]
28    HostIds,
29    #[serde(rename = "topics_ids")]
30    TopicsIds,
31}
32
33impl Expansions {
34    pub fn all() -> HashSet<Self> {
35        let mut result = HashSet::new();
36        result.insert(Self::InvitedUserIds);
37        result.insert(Self::SpeakerIds);
38        result.insert(Self::CreatorId);
39        result.insert(Self::HostIds);
40        result.insert(Self::TopicsIds);
41        result
42    }
43}
44
45impl std::fmt::Display for Expansions {
46    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
47        match self {
48            Self::InvitedUserIds => write!(f, "invited_user_ids"),
49            Self::SpeakerIds => write!(f, "speaker_ids"),
50            Self::CreatorId => write!(f, "creator_id"),
51            Self::HostIds => write!(f, "host_ids"),
52            Self::TopicsIds => write!(f, "topics_ids"),
53        }
54    }
55}
56
57
58#[derive(Debug, Clone, Default)]
59pub struct Api {
60    id: String,
61    expansions: Option<HashSet<Expansions>>,
62    space_fields: Option<HashSet<SpaceFields>>,
63    topic_fields: Option<HashSet<TopicFields>>,
64    user_fields: Option<HashSet<UserFields>>,
65    twapi_options: Option<TwapiOptions>,
66}
67
68impl Api {
69    pub fn new(id: &str) -> Self {
70        Self {
71            id: id.to_owned(),
72            ..Default::default()
73        }
74    }
75
76    pub fn all(id: &str) -> Self {
77        Self {
78            id: id.to_owned(),
79            expansions: Some(Expansions::all()),
80            space_fields: Some(SpaceFields::all()),
81            topic_fields: Some(TopicFields::all()),
82            user_fields: Some(UserFields::all()),
83            ..Default::default()
84        }
85    }
86
87    pub fn expansions(mut self, value: HashSet<Expansions>) -> Self {
88        self.expansions = Some(value);
89        self
90    }
91
92    pub fn space_fields(mut self, value: HashSet<SpaceFields>) -> Self {
93        self.space_fields = Some(value);
94        self
95    }
96
97    pub fn topic_fields(mut self, value: HashSet<TopicFields>) -> Self {
98        self.topic_fields = Some(value);
99        self
100    }
101
102    pub fn user_fields(mut self, value: HashSet<UserFields>) -> Self {
103        self.user_fields = Some(value);
104        self
105    }
106
107    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
108        self.twapi_options = Some(value);
109        self
110    }
111
112    pub fn build(&self, authentication: &impl Authentication) -> RequestBuilder {
113        let mut query_parameters = vec![];
114        if let Some(expansions) = self.expansions.as_ref() {
115            query_parameters.push(("expansions", expansions.iter().join(",")));
116        }
117        if let Some(space_fields) = self.space_fields.as_ref() {
118            query_parameters.push(("space.fields", space_fields.iter().join(",")));
119        }
120        if let Some(topic_fields) = self.topic_fields.as_ref() {
121            query_parameters.push(("topic.fields", topic_fields.iter().join(",")));
122        }
123        if let Some(user_fields) = self.user_fields.as_ref() {
124            query_parameters.push(("user.fields", user_fields.iter().join(",")));
125        }
126        let client = reqwest::Client::new();
127        let url = make_url(&self.twapi_options, &URL.replace(":id", &self.id));
128        let builder = client.get(&url).query(&query_parameters);
129        authentication.execute(
130            builder,
131            "GET",
132            &url,
133            &query_parameters
134                .iter()
135                .map(|it| (it.0, it.1.as_str()))
136                .collect::<Vec<_>>(),
137        )
138    }
139
140    pub async fn execute(
141        &self,
142        authentication: &impl Authentication,
143    ) -> Result<(Response, Headers), Error> {
144        execute_twitter(|| self.build(authentication), &self.twapi_options).await
145    }
146}
147
148#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
149pub struct Response {
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub data: Option<Spaces>,
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub errors: Option<Vec<Errors>>,
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub includes: Option<Includes>,
156    #[serde(flatten)]
157    pub extra: std::collections::HashMap<String, serde_json::Value>,
158}
159
160impl Response {
161    pub fn is_empty_extra(&self) -> bool {
162        let res = self.extra.is_empty()
163            && self
164                .data
165                .as_ref()
166                .map(|it| it.is_empty_extra())
167                .unwrap_or(true)
168            && self
169                .errors
170                .as_ref()
171                .map(|it| it.iter().all(|item| item.is_empty_extra()))
172                .unwrap_or(true)
173            && self
174                .includes
175                .as_ref()
176                .map(|it| it.is_empty_extra())
177                .unwrap_or(true);
178        if !res {
179            println!("Response {:?}", self.extra);
180        }
181        res
182    }
183}