Skip to main content

synd_api/client/github/
client.rs

1use std::{fmt::Debug, time::Duration};
2
3use graphql_client::{GraphQLQuery, Response};
4use reqwest::header::{self, HeaderValue};
5use serde::{Serialize, de::DeserializeOwned};
6use thiserror::Error;
7use tracing::instrument;
8
9use crate::{client::github::query, config};
10
11#[derive(Debug, Error)]
12pub enum GithubClientError {
13    #[error(transparent)]
14    Reqwest(#[from] reqwest::Error),
15    #[error(transparent)]
16    InvalidHeader(#[from] header::InvalidHeaderValue),
17    #[error("github graphql error: {errors:?}")]
18    Graphql { errors: Vec<graphql_client::Error> },
19    #[error("unexpected github graphql response")]
20    UnexpectedResponse,
21}
22
23#[derive(Clone)]
24pub struct GithubClient {
25    client: reqwest::Client,
26    endpoint: Option<&'static str>,
27}
28
29impl GithubClient {
30    const ENDPOINT: &'static str = "https://api.github.com/graphql";
31
32    /// Construct `GithubClient`.
33    pub fn new() -> Result<Self, GithubClientError> {
34        let client = reqwest::ClientBuilder::new()
35            .user_agent(config::USER_AGENT)
36            .timeout(Duration::from_secs(10))
37            .connect_timeout(Duration::from_secs(10))
38            .build()?;
39
40        Ok(Self {
41            client,
42            endpoint: None,
43        })
44    }
45
46    #[must_use]
47    pub fn with_endpoint(self, endpoint: &'static str) -> Self {
48        Self {
49            endpoint: Some(endpoint),
50            ..self
51        }
52    }
53
54    #[instrument(name = "github::authenticate", skip_all)]
55    pub async fn authenticate(&self, access_token: &str) -> Result<String, GithubClientError> {
56        let variables = query::authenticate::Variables {};
57        let request = query::Authenticate::build_query(variables);
58        let response: query::authenticate::ResponseData =
59            self.request(access_token, &request).await?;
60
61        Ok(response.viewer.email)
62    }
63
64    async fn request<Body, ResponseData>(
65        &self,
66        access_token: &str,
67        body: &Body,
68    ) -> Result<ResponseData, GithubClientError>
69    where
70        Body: Serialize + ?Sized,
71        ResponseData: DeserializeOwned + Debug,
72    {
73        let mut auth_header = HeaderValue::try_from(format!("bearer {access_token}"))?;
74        auth_header.set_sensitive(true);
75
76        let res: Response<ResponseData> = self
77            .client
78            .post(self.endpoint.unwrap_or(Self::ENDPOINT))
79            .header(header::AUTHORIZATION, auth_header)
80            .json(&body)
81            .send()
82            .await?
83            .error_for_status()?
84            .json()
85            .await?;
86
87        match (res.data, res.errors) {
88            (_, Some(errs)) if !errs.is_empty() => Err(GithubClientError::Graphql { errors: errs }),
89            (Some(data), _) => Ok(data),
90            _ => Err(GithubClientError::UnexpectedResponse),
91        }
92    }
93}