oauth2_twitch/extensions/
user_info_endpoint.rs

1use oauth2_client::{
2    extensions::{EndpointParseResponseError, EndpointRenderRequestError, UserInfo},
3    re_exports::{serde_json, Body, Endpoint, Request, Response},
4};
5
6use super::internal_users_endpoint::{Users, UsersEndpoint, UsersEndpointError};
7
8//
9#[derive(Debug, Clone)]
10pub struct TwitchUserInfoEndpoint {
11    inner: UsersEndpoint,
12}
13impl TwitchUserInfoEndpoint {
14    pub fn new(access_token: impl AsRef<str>, client_id: impl AsRef<str>) -> Self {
15        Self {
16            inner: UsersEndpoint::new(access_token, client_id),
17        }
18    }
19}
20
21impl Endpoint for TwitchUserInfoEndpoint {
22    type RenderRequestError = EndpointRenderRequestError;
23
24    type ParseResponseOutput = UserInfo;
25    type ParseResponseError = EndpointParseResponseError;
26
27    fn render_request(&self) -> Result<Request<Body>, Self::RenderRequestError> {
28        self.inner.render_request().map_err(Into::into)
29    }
30
31    fn parse_response(
32        &self,
33        response: Response<Body>,
34    ) -> Result<Self::ParseResponseOutput, Self::ParseResponseError> {
35        UserInfo::try_from(self.inner.parse_response(response)?)
36            .map_err(EndpointParseResponseError::ToOutputFailed)
37    }
38}
39
40//
41impl From<UsersEndpointError> for EndpointRenderRequestError {
42    fn from(err: UsersEndpointError) -> Self {
43        match err {
44            UsersEndpointError::MakeRequestFailed(err) => Self::MakeRequestFailed(err),
45            UsersEndpointError::DeResponseBodyFailed(err) => Self::Other(Box::new(err)),
46        }
47    }
48}
49impl From<UsersEndpointError> for EndpointParseResponseError {
50    fn from(err: UsersEndpointError) -> Self {
51        match err {
52            UsersEndpointError::MakeRequestFailed(err) => Self::Other(Box::new(err)),
53            UsersEndpointError::DeResponseBodyFailed(err) => Self::DeResponseBodyFailed(err),
54        }
55    }
56}
57
58//
59impl TryFrom<Users> for UserInfo {
60    type Error = Box<dyn std::error::Error + Send + Sync>;
61
62    fn try_from(users: Users) -> Result<Self, Self::Error> {
63        let user = users.data.first().cloned().ok_or("not found user")?;
64
65        Ok(Self {
66            uid: user.id.to_owned(),
67            name: Some(user.login.to_owned()),
68            email: user.email.to_owned(),
69            raw: serde_json::to_value(user)
70                .map(|x| x.as_object().cloned())?
71                .ok_or_else(|| "unreachable".to_owned())?,
72        })
73    }
74}