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
extern crate reqwest;
extern crate serde_json;

pub mod address;
pub mod geo;
pub mod company;
use model::Model;
use utils::*;
use post::Post;


#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct User {
    pub id: i32,
    pub name: String,
    pub username: String,
    pub email: String,
    pub address: address::Address,
    pub phone: String,
    pub website: String,
    pub company: company::Company
}

impl PartialEq for User {
    fn eq(&self, other: &User) -> bool {
        self.id == other.id
    } 
}

impl Model<User> for User {
    fn find(id: i32) -> Option<User> {
       let mut response = reqwest::get(&format!("{}users/{}", get_endpoint(),id)).expect("Failed to send a request");
       if response.status() == reqwest::StatusCode::Ok {
           match response.text() {
               Ok(text) => {
                   let user: User = serde_json::from_str(&text).expect("Failed to parse the json");
                   Some(user)
               },
               Err(_) => panic!("Error")
           }
       } else {
          None
       }
   }

    fn all() -> Vec<User> {
        let mut response = reqwest::get(&format!("{}users", get_endpoint())).expect("Failed to send a request");
        let text = response.text().expect("Failed to get the body");
        let users: Vec<User> = serde_json::from_str(&text).expect("Error parsing the json");
        users
    }

    fn create(model: User) -> Result<(), reqwest::Error> {
        let body = serde_json::to_string(&model).expect("Failed to serialize the model");
        reqwest::Client::new()
            .post(&format!("{}/users", get_endpoint()))
            .body(body)
            .send()?;
        Ok(())
    }

}

impl User {
    /// Gets all the articles posted by this user
    /// 
    /// # Example
    /// ```
    /// use jplaceholder::Model;
    /// use jplaceholder::User;
    /// use jplaceholder::Post;
    /// 
    /// let user = match User::find(1) {
    ///     Some(u) => u,
    ///     None => panic!("user not found")
    /// };
    /// let posts: Vec<Post> = user.posts().expect("This user has posted no article");
    /// println!("{} posted {} articles", user.name, posts.len());
    /// ```
    pub fn posts(&self) ->Option<Vec<Post>> {
        let posts: Vec<Post> = Post::all().into_iter().filter(|p| p.user_id == self.id).collect();
        if posts.len() >= 1 {
            Some(posts)
        } else {
            None
        }
    }
}