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
use super::*;

#[derive(Serialize)]
struct Request {
    user: RequestUser,
    verify: Option<RequestVerify>,
}

#[derive(Serialize)]
struct RequestUser {
    email: String,
    password: String,
    first_name: Option<String>,
    last_name: Option<String>,
    birthday: Option<time::Date>,
}

#[derive(Serialize)]
struct RequestVerify {
    sender_name: String,
    // The callback URL to which a query string will be appended containing the verification token
    // Example Input: https://example.com/verify
    // Example Output: https://example.com/verify?token=123456
    callback: String,
}

#[derive(Deserialize)]
struct Response {
    id: i32,
}

impl Client {
    // Returns ID of created user
    pub async fn create_user(
        &self,
        email: String,
        password: String,
        first_name: Option<String>,
        last_name: Option<String>,
        birthday: Option<time::Date>,
        sender_name: Option<String>,
        callback: Option<String>,
    ) -> Result<Option<i32>, Box<dyn std::error::Error>> {
        let mut data = Request {
            user: RequestUser {
                email,
                password,
                first_name,
                last_name,
                birthday,
            },
            verify: None,
        };

        if sender_name.is_some() && callback.is_some() {
            data.verify = Some(RequestVerify {
                sender_name: sender_name.unwrap(),
                callback: callback.unwrap(),
            });
        }

        let res = req()
            .post(self.endpoint("/v1/users", vec![]))
            .json(&data)
            .send()
            .await?;

        match res.status() {
            StatusCode::CONFLICT => Ok(None),
            StatusCode::BAD_REQUEST => Err("Bad Request".into()),
            StatusCode::OK => Ok(Some(res.json::<Response>().await?.id)),
            _ => Err("Unknown Response Status Code".into()),
        }
    }
}