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



extern crate reqwest;
extern crate serde_json;

use model::Model;
use utils::*;

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Post {
    pub user_id: i32,
    pub id: i32,
    pub title: String,
    pub body: String
}

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


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

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

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

}