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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
use serde_json;
use serde_json::Value;

use KintoClient;
use error::KintoError;
use paths::Paths;
use request::{GetCollection, DeleteCollection, GetRecord, CreateRecord,
              UpdateRecord, DeleteRecord, KintoRequest};
use response::ResponseWrapper;
use resource::Resource;
use bucket::Bucket;
use record::Record;
use utils::{unwrap_collection_ids, extract_ids_from_path};


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


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

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

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

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

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

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


impl Collection {

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

    pub fn record(self, id: &'static str) -> Record {
        return Record::new(self.client.clone(), self, id);
    }

    /// Create a new empty record with a generated id.
    pub fn new_record(&mut self) -> Result<Record, KintoError> {
        match self.create_record_request().send() {
            Ok(wrapper) => Ok(wrapper.into()),
            Err(value) => return Err(value)
        }
    }

    /// List the names of all available records.
    pub fn list_records(&mut self) -> Result<Vec<String>, KintoError> {
        let response = try!(self.list_records_request().send());
        // XXX: we should follow possible subrequests
        Ok(unwrap_collection_ids(response))
    }

    /// Delete all available records.
    pub fn delete_records(&mut self) -> Result<(), KintoError> {
        try!(self.delete_records_request().send());
        Ok(())
    }

    pub fn list_records_request(&mut self) -> GetCollection {
        GetCollection::new(self.client.clone(),
                           Paths::Records(self.bucket.id.as_str(),
                                          self.id.as_str()).into())
    }

    pub fn delete_records_request(&mut self) -> DeleteCollection {
        DeleteCollection::new(self.client.clone(),
                           Paths::Records(self.bucket.id.as_str(),
                                          self.id.as_str()).into())
    }

    pub fn create_record_request(&mut self) -> CreateRecord {
        CreateRecord::new(self.client.clone(),
                           Paths::Records(self.bucket.id.as_str(),
                                          self.id.as_str()).into())
    }
}


impl Resource for Collection {

    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::Collection(self.bucket.id.as_str(),
                                         self.id.as_str()).into())
    }

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

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


impl From<ResponseWrapper> for Collection {
    fn from(wrapper: ResponseWrapper) -> Self {

        let path_ids = extract_ids_from_path(wrapper.path);
        let bucket_id = path_ids["buckets"].clone().unwrap();

        let collection: Collection = serde_json::from_value(wrapper.body).unwrap();
        let data = collection.data.clone().unwrap();

        let timestamp = data["last_modified"].as_u64().unwrap();

        Collection {
            client: wrapper.client.clone(),
            bucket: Bucket::new(wrapper.client, bucket_id.as_str()),
            id: data["id"].as_str().unwrap().to_owned(),
            timestamp: Some(timestamp.into()),
            ..collection
        }
    }
}


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

    #[test]
    fn test_create_collection() {
        let mut collection = setup_collection();
        collection.data = json!({"good": true}).into();

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

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

    #[test]
    fn test_create_collection_fails_on_existing() {
        let mut collection = setup_collection();

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

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

    #[test]
    fn test_load_collection() {
        let mut collection = setup_collection();
        collection.set().unwrap();
        let create_data = collection.data.clone().unwrap();

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

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


        assert_eq!(create_data, load_data);
    }

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

    #[test]
    fn test_update_collection() {
        let mut collection = setup_collection();

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

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

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

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

    #[test]
    fn test_get_record() {
        let collection = setup_collection();
        let record = collection.record("entrecote");
        assert_eq!(record.id, "entrecote");
        assert!(record.data == None);
    }

    #[test]
    fn test_new_record() {
        let mut collection = setup_collection();
        collection.create().unwrap();
        let record = collection.new_record().unwrap();
        assert!(record.data != None);
        assert_eq!(collection.id.as_str(),
                   collection.data.unwrap()["id"].as_str().unwrap());
    }

    #[test]
    fn test_list_records() {
        let mut collection = setup_collection();
        collection.create().unwrap();
        assert_eq!(collection.list_records().unwrap().len(), 0);
        collection.new_record().unwrap();
        assert_eq!(collection.list_records().unwrap().len(), 1);
    }

    #[test]
    fn test_delete_records() {
        let mut collection = setup_collection();
        collection.create().unwrap();
        collection.new_record().unwrap();
        assert_eq!(collection.list_records().unwrap().len(), 1);
        collection.delete_records().unwrap();
        assert_eq!(collection.list_records().unwrap().len(), 0);
    }

    #[test]
    fn test_list_records_request() {
        let mut collection = setup_collection();
        let request = collection.list_records_request();
        assert_eq!(request.preparer.path, "/buckets/food/collections/meat/records");
    }

    #[test]
    fn test_delete_records_request() {
        let mut collection = setup_collection();
        let request = collection.delete_records_request();
        assert_eq!(request.preparer.path, "/buckets/food/collections/meat/records");
    }

    #[test]
    fn test_create_records_request() {
        let mut collection = setup_collection();
        let request = collection.create_record_request();
        assert_eq!(request.preparer.path, "/buckets/food/collections/meat/records");
    }
}