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
//! Creating registration calls and interpreting registration results.
use std::borrow::Cow;

use crate::{
    data,
    error::{ApiError, Result},
    EndpointResult,
};

/// Registration details
#[derive(Serialize, Clone, Hash, Debug)]
pub struct RegistrationArgs<'a> {
    /// The username to register.
    username: Cow<'a, str>,
    /// The email to register with, or None.
    email: Option<Cow<'a, str>>,
    /// The password to register with.
    password: Cow<'a, str>,
}

impl<'a> RegistrationArgs<'a> {
    /// Create a new registration details with the given username and password
    pub fn new<T, U>(username: T, password: U) -> Self
    where
        T: Into<Cow<'a, str>>,
        U: Into<Cow<'a, str>>,
    {
        RegistrationArgs {
            username: username.into(),
            email: None,
            password: password.into(),
        }
    }
    /// Create a new registration details with the given username and password
    pub fn with_email<T, U, V>(username: T, password: U, email: V) -> Self
    where
        T: Into<Cow<'a, str>>,
        U: Into<Cow<'a, str>>,
        V: Into<Cow<'a, str>>,
    {
        RegistrationArgs {
            username: username.into(),
            password: password.into(),
            email: Some(email.into()),
        }
    }
}

/// Raw registration response.
#[derive(serde_derive::Deserialize, Clone, Hash, Debug)]
pub(crate) struct Response {
    ok: i32,
}

/// Registration success response.
#[derive(Clone, Hash, Debug)]
pub struct RegistrationSuccess {
    /// Phantom data in order to allow adding any additional fields in the future.
    _non_exhaustive: (),
}

impl EndpointResult for RegistrationSuccess {
    type RequestResult = Response;
    type ErrorResult = data::ApiError;

    fn from_raw(raw: Response) -> Result<RegistrationSuccess> {
        let Response { ok } = raw;

        if ok != 1 {
            return Err(ApiError::NotOk(ok).into());
        }

        Ok(RegistrationSuccess {
            _non_exhaustive: (),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::RegistrationSuccess;
    use crate::EndpointResult;
    use serde_json;

    fn test_parse(json: serde_json::Value) {
        let response = serde_json::from_value(json).unwrap();

        let _ = RegistrationSuccess::from_raw(response).unwrap();
    }

    #[test]
    fn parse_sample() {
        test_parse(json! ({
            "ok": 1,
        }));
    }
}