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
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::borrow::Cow;
use std::ops::{Index, IndexMut};

/// Trait to deal with typed CouchDB documents.
pub trait TypedCouchDocument: DeserializeOwned + Serialize + Sized {
    /// get the _id field
    fn get_id(&self) -> Cow<str>;
    /// get the _rev field
    fn get_rev(&self) -> Cow<str>;
    /// set the _rev field
    fn set_rev(&mut self, rev: &str);
    /// set the _id field
    fn set_id(&mut self, rev: &str);
    /// merge the _id and _rev from the other document with this one
    fn merge_ids(&mut self, other: &Self);
}

/// Allows dealing with _id and _rev fields in untyped (Value) documents
impl TypedCouchDocument for Value {
    fn get_id(&self) -> Cow<str> {
        let id: String = json_extr!(self["_id"]);
        Cow::from(id)
    }

    fn get_rev(&self) -> Cow<str> {
        let rev: String = json_extr!(self["_rev"]);
        Cow::from(rev)
    }

    fn set_rev(&mut self, rev: &str) {
        if let Some(o) = self.as_object_mut() {
            o.insert("_rev".to_string(), Value::from(rev));
        }
    }

    fn set_id(&mut self, id: &str) {
        if let Some(o) = self.as_object_mut() {
            o.insert("_id".to_string(), Value::from(id));
        }
    }

    fn merge_ids(&mut self, other: &Self) {
        self.set_id(&other.get_id());
        self.set_rev(&other.get_rev());
    }
}

/// Memory-optimized, iterable document collection, mostly returned in calls
/// that involve multiple documents results Can target a specific index through
/// implementation of `Index` and `IndexMut`
#[derive(PartialEq, Debug, Clone)]
pub struct DocumentCollection<T: TypedCouchDocument> {
    pub offset: Option<u32>,
    pub rows: Vec<T>,
    pub total_rows: u32,
    pub bookmark: Option<String>,
}

impl<T: TypedCouchDocument> Default for DocumentCollection<T> {
    fn default() -> Self {
        DocumentCollection {
            offset: None,
            rows: vec![],
            total_rows: 0,
            bookmark: None,
        }
    }
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(bound(deserialize = "T: TypedCouchDocument"))]
pub struct AllDocsResponse<T: TypedCouchDocument> {
    pub total_rows: Option<u32>,
    pub offset: Option<u32>,
    pub rows: Vec<DocResponse<T>>,
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(bound(deserialize = "T: TypedCouchDocument"))]
pub struct DocResponse<T: TypedCouchDocument> {
    pub id: Option<String>,
    pub key: Option<Value>,
    pub value: Option<DocResponseValue>,
    pub error: Option<String>,
    pub doc: Option<T>,
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct DocResponseValue {
    pub rev: String,
}

impl<T: TypedCouchDocument> DocumentCollection<T> {
    pub fn new(doc: AllDocsResponse<T>) -> DocumentCollection<T> {
        let rows = doc.rows;
        let items: Vec<T> = rows
            .into_iter()
            .filter_map(|d| {
                if d.error.is_some() {
                    // remove errors
                    None
                } else {
                    // Remove _design documents
                    if let Some(doc) = d.doc {
                        if doc.get_id().starts_with('_') {
                            None
                        } else {
                            Some(doc)
                        }
                    } else {
                        // no documents retrieved
                        None
                    }
                }
            })
            .collect();

        DocumentCollection {
            offset: doc.offset,
            total_rows: items.len() as u32,
            rows: items,
            bookmark: Option::None,
        }
    }

    pub fn new_from_documents(docs: Vec<T>, bookmark: Option<String>) -> DocumentCollection<T> {
        let len = docs.len() as u32;
        DocumentCollection {
            offset: Some(0),
            total_rows: len,
            rows: docs,
            bookmark,
        }
    }

    pub fn new_from_values(docs: Vec<Value>, bookmark: Option<String>) -> DocumentCollection<T> {
        let len = docs.len() as u32;

        DocumentCollection {
            offset: Some(0),
            total_rows: len,
            rows: docs
                .into_iter()
                .filter_map(|d| serde_json::from_value::<T>(d).ok())
                .collect(),
            bookmark,
        }
    }

    /// Returns raw JSON data from documents
    pub fn get_data(&self) -> &Vec<T> {
        &self.rows
    }
}

impl<T: TypedCouchDocument> Index<usize> for DocumentCollection<T> {
    type Output = T;

    fn index(&self, index: usize) -> &T {
        &self.rows.get(index).unwrap()
    }
}

impl<T: TypedCouchDocument> IndexMut<usize> for DocumentCollection<T> {
    fn index_mut(&mut self, index: usize) -> &mut T {
        self.rows.get_mut(index).unwrap()
    }
}

#[cfg(test)]
mod tests {
    use crate as couch_rs;
    use crate::document::TypedCouchDocument;
    use couch_rs_derive::CouchDocument;
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize, CouchDocument, Debug, Default)]
    struct TestDocument {
        #[serde(skip_serializing_if = "String::is_empty")]
        pub _id: String,
        #[serde(skip_serializing_if = "String::is_empty")]
        pub _rev: String,
    }

    #[test]
    fn test_derive_couch_document() {
        let doc = TestDocument {
            _id: "1".to_string(),
            _rev: "2".to_string(),
        };
        let id = doc.get_id();
        let rev = doc.get_rev();
        assert_eq!(id, "1");
        assert_eq!(rev, "2");
    }
}