1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#[cfg(not(test))]
use crate::url;
use crate::{check_for_errors, schema::users::contextual_info, GithubClient};
use serde_json::from_str;
use std::error::Error;

#[non_exhaustive]
pub struct Users<'a> {
    #[cfg_attr(test, allow(dead_code))]
    client: &'a GithubClient<'a>,
}

use crate::schema::{
    users::{list, single},
    GitHubError,
};
impl<'a> Users<'a> {
    pub(crate) fn new(client: &'a GithubClient<'a>) -> Self {
        Users { client }
    }

    /// Fetches a list of users.
    pub async fn list(&self, cfg: Option<list::Params>) -> Result<Vec<list::User>, Box<dyn Error>> {
        #[cfg(test)]
        let text = crate::mock_response!(&self, "users", "list", cfg);
        #[cfg(not(test))]
        let text = {
            let result = self
                .client
                .reqwest_client
                .get(url!(self, "/users"))
                .query(&cfg)
                .send()
                .await?;
            result.text().await?
        };
        let json_result = from_str::<Vec<list::User>>(&text);
        match json_result {
            Ok(data) => Ok(data),
            Err(err) => {
                if err.is_data() {
                    let error_data = from_str::<GitHubError>(&text)?;
                    check_for_errors!(error_data, err);
                } else {
                    Err(err.into())
                }
            }
        }
    }

    /// Fetches a specific user.
    /// If authenticated, it will show a few more fields.
    /// If the current authenticated user is the same as the user being fetched, a few more fields will exist.
    /// # Errors
    /// Will error if the user does not exist.
    pub async fn user(&self, username: &str) -> Result<single::User, Box<dyn Error>> {
        #[cfg(test)]
        let text = crate::mock_response!(&self, "users", "user", username);
        #[cfg(not(test))]
        let text = {
            let result = self
                .client
                .reqwest_client
                .get(url!(self, "/users/{}", username))
                .send()
                .await?;
            result.text().await?
        };

        match from_str::<single::User>(&text) {
            Ok(data) => Ok(data),
            Err(err) => {
                if err.is_data() {
                    let error_data = from_str::<GitHubError>(&text)?;
                    check_for_errors!(error_data, err);
                } else {
                    Err(err.into())
                }
            }
        }
    }

    #[cfg(any(feature = "auth", doc))]
    #[cfg_attr(docsrs, doc(cfg(feature = "auth")))]
    /// Fetches contextual info (like the hovercard you see on github). Requires auth.
    /// It can either work with the username alone (and then it will fetch profile data), or it can work with a subject type (like "repository") and id (the repository's id on the API).
    /// # Errors
    /// Will error if the user doesn't exist.
    pub async fn contextual_info(
        &self,
        username: &str,
        cfg: Option<contextual_info::Params>,
    ) -> Result<contextual_info::User, Box<dyn Error>> {
        #[cfg(test)]
        let text = crate::mock_response!(&self, "users", "contextual_info", (username, cfg));
        #[cfg(not(test))]
        let text = {
            let result = self
                .client
                .reqwest_client
                .get(url!(self, "/users/{}/hovercard", username))
                .query(&cfg)
                .send()
                .await?;
            result.text().await?
        };

        match from_str::<contextual_info::User>(&text) {
            Ok(data) => Ok(data),
            Err(err) => {
                if err.is_data() {
                    let error_data = from_str::<GitHubError>(&text)?;
                    check_for_errors!(error_data, err);
                } else {
                    Err(err.into())
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "auth")]
    use crate::constants::FAKE_TOKEN;

    use super::*;

    #[tokio::test]
    async fn list_works() {
        let client = GithubClient::new(
            #[cfg(feature = "enterprise")]
            "https://something.com/api/v3",
            #[cfg(feature = "auth")]
            FAKE_TOKEN,
        )
        .unwrap();

        let users = Users::new(&client);
        let data = users.list(None).await.unwrap();
        assert_eq!(data[0].login, "mojombo");
        assert_eq!(data[0].id, 1);
    }

    #[tokio::test]
    async fn single_works() {
        let client = GithubClient::new(
            #[cfg(feature = "enterprise")]
            "https://something.com/api/v3",
            #[cfg(feature = "auth")]
            FAKE_TOKEN,
        )
        .unwrap();
        let users = Users::new(&client);
        let data = users.user("mojombo").await.unwrap();
        assert_eq!(data.login, "mojombo");
    }

    #[tokio::test]
    #[cfg(feature = "auth")]
    async fn context_info_works() {
        #[cfg(feature = "auth")]
        let client = GithubClient::new(
            #[cfg(feature = "enterprise")]
            "https://something.com/api/v3",
            FAKE_TOKEN,
        )
        .unwrap();
        let users = Users::new(&client);
        let data = users.contextual_info("mojombo", None).await.unwrap();
        assert_eq!(data.contexts[0].message, "Member of @toml-lang");
    }
}