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

#[derive(Serialize)]
struct Request {
    name: Option<String>,
}

#[derive(Deserialize, Serialize, Debug)]
pub struct Returns {
    pub id: i32,
    pub secret_key: String,
    pub created: time::PrimitiveDateTime,
}

impl Client {
    // Returns ID of created token
    pub async fn create_token(
        &self,
        user: i32,
        name: Option<String>,
    ) -> Result<Option<Returns>, Box<dyn std::error::Error>> {
        let res = req()
            .post(self.endpoint("/v1/users/{}/tokens", vec![user.to_string()]))
            .json(&Request { name })
            .send()
            .await?;

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