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
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use serde_json;
use serde_json::Value;

use KintoClient;
use paths::Paths;
use request::{GetRecord, UpdateRecord, DeleteRecord};
use response::ResponseWrapper;
use resource::Resource;
use bucket::Bucket;
use collection::Collection;
use utils::extract_ids_from_path;


#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RecordPermissions {
    #[serde(default="Vec::new")]
    pub read: Vec<String>,
    #[serde(default="Vec::new")]
    pub write: Vec<String>,
}


#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Record {
    #[serde(skip_serializing_if="Option::is_none")]
    pub data: Option<Value>,

    #[serde(skip_serializing_if="Option::is_none")]
    pub permissions: Option<RecordPermissions>,

    #[serde(skip_serializing, skip_deserializing)]
    pub client: KintoClient,

    #[serde(skip_serializing, skip_deserializing)]
    pub bucket: Bucket,

    #[serde(skip_serializing, skip_deserializing)]
    pub collection: Collection,

    #[serde(skip_serializing, skip_deserializing)]
    pub id: String,

    #[serde(skip_serializing, skip_deserializing)]
    pub timestamp: Option<u64>,
}


impl Record {

    /// Create a new record resource.
    pub fn new<'a>(client: KintoClient, collection: Collection, id: &'a str) -> Self {
        Record {
            client: client,
            bucket: collection.bucket.clone(),
            collection: collection,
            id: id.to_owned(),
            timestamp: None,
            data: None,
            permissions: None
        }
    }
}


impl Resource for Record {

    fn unwrap_response(&mut self, wrapper: ResponseWrapper){
        *self = wrapper.into()
    }

    fn get_timestamp(&mut self) -> Option<u64> {
        self.timestamp
    }

    fn load_request(&mut self) -> GetRecord {
        GetRecord::new(self.client.clone(),
                       Paths::Record(self.bucket.id.as_str(),
                                     self.collection.id.as_str(),
                                     self.id.as_str()).into())
    }

    fn update_request(&mut self) -> UpdateRecord {
        UpdateRecord::new(self.client.clone(),
                          Paths::Record(self.bucket.id.as_str(),
                                        self.collection.id.as_str(),
                                        self.id.as_str()).into())
    }

    fn delete_request(&mut self) -> DeleteRecord {
        DeleteRecord::new(self.client.clone(),
                          Paths::Record(self.bucket.id.as_str(),
                                        self.collection.id.as_str(),
                                        self.id.as_str()).into())
    }
}


impl From<ResponseWrapper> for Record {
    fn from(wrapper: ResponseWrapper) -> Self {
        let path_ids = extract_ids_from_path(wrapper.path);

        let bucket_id = path_ids["buckets"].clone().unwrap();
        let collection_id = path_ids["collections"].clone().unwrap();

        let bucket = Bucket::new(wrapper.client.clone(),
                                 bucket_id.as_str());
        let collection = Collection::new(wrapper.client.clone(),
                                         bucket.clone(),
                                         collection_id.as_str());;
        let record: Record = serde_json::from_value(wrapper.body).unwrap();
        let data = record.data.clone().unwrap();

        let timestamp = data["last_modified"].as_u64().unwrap();
        Record {
            client: wrapper.client,
            bucket: bucket,
            collection: collection,
            id: data["id"].as_str().unwrap().to_owned(),
            timestamp: Some(timestamp.into()),
            ..record
        }
    }
}


#[cfg(test)]
mod test_record {
    use resource::Resource;
    use utils::tests::{setup_record, setup_collection};

    #[test]
    fn test_create_record() {
        let mut record = setup_record();
        record.data = json!({"good": true}).into();

        record.create().unwrap();
        let data = record.data.unwrap().to_owned();

        assert_eq!(data["id"], "entrecote");
        assert_eq!(data["good"].as_bool().unwrap(), true);
    }

    #[test]
    fn test_create_record_fails_on_existing() {
        let mut record = setup_record();

        // Create
        record.create().unwrap();

        // Tries to create again
        match record.create() {
            Ok(_) => panic!(""),
            Err(_) => ()
        }
    }

    #[test]
    fn test_load_record() {
        let mut record = setup_record();
        record.set().unwrap();
        let create_data = record.data.clone().unwrap();

        // Cleanup stored data to make sure load work
        record.data = json!({}).into();

        record.load().unwrap();
        let load_data = record.data.unwrap();


        assert_eq!(create_data, load_data);
    }

    #[test]
    fn test_load_record_fails_on_not_existing() {
        let mut record = setup_record();
        match record.load() {
            Ok(_) => panic!(""),
            Err(_) => ()
        }
    }

    #[test]
    fn test_update_record() {
        let mut record = setup_record();

        record.create().unwrap();
        let create_data = record.data.clone().unwrap();

        record.update().unwrap();
        let update_data = record.data.unwrap();

        assert_eq!(create_data["id"], update_data["id"]);
        assert!(create_data["last_modified"] != update_data["last_modified"]);
    }

    #[test]
    fn test_update_record_fails_on_not_existing() {
        let client = setup_collection();
        let mut record = client.record("food");
        match record.update() {
            Ok(_) => panic!(""),
            Err(_) => ()
        }
    }
}