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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! # Firestore Document Access
//!
//! Interact with Firestore documents.
//! Please check the root page of this documentation for examples.

macro_rules! firebase_url_query {
    () => {
        "https://firestore.googleapis.com/v1/projects/{}/databases/(default)/documents:runQuery"
    };
}
macro_rules! firebase_url_base {
    () => {
        "https://firestore.googleapis.com/v1/{}"
    };
}
macro_rules! firebase_url_extended {
    () => {
        "https://firestore.googleapis.com/v1/projects/{}/databases/(default)/documents/{}/{}"
    };
}
macro_rules! firebase_url {
    () => {
        "https://firestore.googleapis.com/v1/projects/{}/databases/(default)/documents/{}?"
    };
}

use super::dto;
use super::errors::{FirebaseError, Result};
use super::firebase_rest_to_rust::{document_to_pod, pod_to_document};
use super::FirebaseAuthBearer;

use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// This is returned by the write() method in a successful case.
///
/// This structure contains the document id of the written document.
#[derive(Serialize, Deserialize)]
pub struct WriteResult {
    ///
    pub create_time: Option<chrono::DateTime<chrono::Utc>>,
    pub update_time: Option<chrono::DateTime<chrono::Utc>>,
    pub document_id: String,
}

///
/// Write a document to a given collection.
///
/// ## Arguments
/// * 'auth' The authentication token
/// * 'path' The document path / collection; For example "my_collection" or "a/nested/collection"
/// * 'document_id' The document id. Make sure that you do not include the document id to the path argument.
/// * 'document' The document
pub fn write<'a, T, BEARER>(
    auth: &'a mut BEARER,
    path: &str,
    document_id: Option<&str>,
    document: &T,
) -> Result<WriteResult>
where
    T: Serialize,
    for<'c> BEARER: FirebaseAuthBearer<'c>,
{
    let url = match document_id {
        Some(document_id) => format!(
            firebase_url_extended!(),
            auth.projectid(),
            path,
            document_id
        ),
        None => format!(firebase_url!(), auth.projectid(), path),
    };

    let firebase_document = pod_to_document(&document)?;

    let builder = if document_id.is_some() {
        Client::new().patch(&url)
    } else {
        Client::new().post(&url)
    };

    let mut resp = builder
        .bearer_auth(auth.bearer().to_owned())
        .json(&firebase_document)
        .send()?;

    if resp.status() != 200 {
        return Err(FirebaseError::UnexpectedResponse(
            "Firestore write failed: ",
            resp.status(),
            resp.text()?,
            serde_json::to_string_pretty(&firebase_document)?,
        ));
    }
    let result_document: dto::Document = resp.json()?;
    let doc_path = result_document.name.ok_or_else(|| {
        FirebaseError::Generic("Resulting document does not contain a 'name' field")
    })?;
    let document_id = Path::new(&doc_path)
        .file_name()
        .ok_or_else(|| {
            FirebaseError::Generic("Resulting documents 'name' field is not a valid path")
        })?
        .to_str()
        .ok_or_else(|| FirebaseError::Generic("No valid unicode in 'name' field"))?
        .to_owned();

    let create_time = match result_document.create_time {
        Some(f) => Some(
            chrono::DateTime::parse_from_rfc3339(&f)
                .map_err(|_| {
                    FirebaseError::Generic("Failed to parse rfc3339 date from 'create_time' field")
                })?
                .with_timezone(&chrono::Utc),
        ),
        None => None,
    };
    let update_time = match result_document.update_time {
        Some(f) => Some(
            chrono::DateTime::parse_from_rfc3339(&f)
                .map_err(|_| {
                    FirebaseError::Generic("Failed to parse rfc3339 date from 'update_time' field")
                })?
                .with_timezone(&chrono::Utc),
        ),
        None => None,
    };

    Ok(WriteResult {
        document_id,
        create_time,
        update_time,
    })
}

///
/// Read a document of a specific type from a collection by its Firestore document name
///
/// ## Arguments
/// * 'auth' The authentication token
/// * 'document_name' The document path / collection and document id; For example "projects/my_project/databases/(default)/documents/tests/test"
pub fn read_by_name<'a, T, BEARER>(auth: &'a mut BEARER, document_name: &str) -> Result<T>
where
    for<'b> T: Deserialize<'b>,
    for<'c> BEARER: FirebaseAuthBearer<'c>,
{
    let url = format!(firebase_url_base!(), document_name);

    let mut resp = Client::new()
        .get(&url)
        .bearer_auth(auth.bearer().to_owned())
        .send()?;

    if resp.status() != 200 {
        return Err(FirebaseError::UnexpectedResponse(
            "Firestore read failed: ",
            resp.status(),
            resp.text()?,
            serde_json::to_string_pretty(&url)?,
        ));
    }

    let json: dto::Document = resp.json()?;
    Ok(document_to_pod(&json)?)
}

///
/// Read a document of a specific type from a collection
///
/// ## Arguments
/// * 'auth' The authentication token
/// * 'path' The document path / collection; For example "my_collection" or "a/nested/collection"
/// * 'document_id' The document id. Make sure that you do not include the document id to the path argument.
pub fn read<'a, T, BEARER>(auth: &'a mut BEARER, path: &str, document_id: &str) -> Result<T>
where
    for<'b> T: Deserialize<'b>,
    for<'c> BEARER: FirebaseAuthBearer<'c>,
{
    let document_name = format!(
        "projects/{}/databases/(default)/documents/{}/{}",
        auth.projectid(),
        path,
        document_id
    );
    read_by_name(auth, &document_name)
}

/// Use this type to list all documents of a given collection.
///
/// Please note that this API acts as an iterator of same-like documents.
/// This type is not suitable if you want to list documents of different types.
pub struct List<'a, T, BEARER> {
    auth: &'a mut BEARER,
    next_page_token: Option<String>,
    documents: Vec<dto::Document>,
    current: usize,
    done: bool,
    url: String,
    phantom: std::marker::PhantomData<T>,
}

/// List all documents of a given collection.
///
/// Please note that this API acts as an iterator of same-like documents.
/// This type is not suitable if you want to list documents of different types.
///
/// ## Arguments
/// * 'auth' The authentication token
/// * 'path' The document path / collection; For example "my_collection" or "a/nested/collection"
pub fn list<'a, T, BEARER>(auth: &'a mut BEARER, path: &str) -> List<'a, T, BEARER>
where
    for<'c> BEARER: FirebaseAuthBearer<'c>,
{
    List {
        url: format!(firebase_url!(), auth.projectid(), path,),
        auth,
        next_page_token: None,
        documents: vec![],
        current: 0,
        done: false,
        phantom: std::marker::PhantomData,
    }
}

fn get_new_data<'a>(
    url: &str,
    auth: &'a mut dyn FirebaseAuthBearer<'a>,
) -> Result<dto::ListDocumentsResponse> {
    let mut resp = Client::new()
        .get(url)
        .bearer_auth(auth.bearer().to_owned())
        .send()?;

    if resp.status() != 200 {
        return Err(FirebaseError::UnexpectedResponse(
            "Firestore read failed: ",
            resp.status(),
            resp.text()?,
            serde_json::to_string_pretty(&url)?,
        ));
    }

    let json: dto::ListDocumentsResponse = resp.json()?;
    Ok(json)
}

impl<'a, T, BEARER> Iterator for List<'a, T, BEARER>
where
    for<'b> T: Deserialize<'b>,
    for<'c> BEARER: FirebaseAuthBearer<'c>,
{
    type Item = Result<T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        if self.documents.len() <= self.current {
            let url = match &self.next_page_token {
                Some(next_page_token) => format!("{}pageToken={}", self.url, next_page_token),
                None => self.url.clone(),
            };

            let result = get_new_data(&url, self.auth);
            match result {
                Err(e) => {
                    self.done = true;
                    return Some(Err(e));
                }
                Ok(v) => match v.documents {
                    None => return None,
                    Some(documents) => {
                        self.documents = documents;
                        self.current = 0;
                        self.next_page_token = v.next_page_token;
                    }
                },
            };
        }

        let doc = self.documents.get(self.current).unwrap();

        self.current += 1;
        if self.documents.len() <= self.current && self.next_page_token.is_none() {
            self.done = true;
        }

        return Some(document_to_pod(&doc));
    }
}

///
/// Queries the database for specific documents, for example all documents in a collection of the 'type' == "car".
///
/// Please note that this API returns a vector of same-like documents.
/// This method is not suitable if you want to query for different types of documents.
///
/// ## Arguments
/// * 'auth' The authentication token
/// * 'collectionid' The collection id; "my_collection" or "a/nested/collection"
/// * 'value' The query / filter value. For example "car".
/// * 'operator' The query operator. For example "EQUAL".
/// * 'field' The query / filter field. For example "type".
pub fn query<'a, T, BEARER>(
    auth: &'a mut BEARER,
    collectionid: &str,
    value: &str,
    operator: dto::FieldOperator,
    field: &str,
) -> Result<Vec<T>>
where
    for<'b> T: Deserialize<'b>,
    for<'c> BEARER: FirebaseAuthBearer<'c>,
{
    let url = format!(firebase_url_query!(), auth.projectid());

    let query_request = dto::RunQueryRequest {
        structured_query: Some(dto::StructuredQuery {
            select: Some(dto::Projection { fields: None }),
            where_: Some(dto::Filter {
                field_filter: Some(dto::FieldFilter {
                    value: dto::Value {
                        string_value: Some(value.to_owned()),
                        ..Default::default()
                    },
                    op: operator,
                    field: dto::FieldReference {
                        field_path: field.to_owned(),
                    },
                }),
                ..Default::default()
            }),
            from: Some(vec![dto::CollectionSelector {
                collection_id: Some(collectionid.to_owned()),
                ..Default::default()
            }]),
            ..Default::default()
        }),
        ..Default::default()
    };

    let mut resp = Client::new()
        .post(&url)
        .bearer_auth(auth.bearer().to_owned())
        .json(&query_request)
        .send()?;

    if resp.status() != 200 {
        return Err(FirebaseError::UnexpectedResponse(
            "Firestore query failed: ",
            resp.status(),
            resp.text()?,
            serde_json::to_string_pretty(&url)?,
        ));
    }

    let json: Option<Vec<dto::RunQueryResponse>> = resp.json()?;

    let mut dtos: Vec<T> = Vec::new();
    if json.is_none() {
        return Ok(dtos);
    }
    let json = json.unwrap();

    for value in json.iter() {
        if let Some(ref document) = &value.document {
            if document.fields.is_none() && document.name.is_some() {
                let doc: T = read_by_name(auth, &document.name.as_ref().unwrap())?;
                dtos.push(doc);
            } else {
                dtos.push(document_to_pod(document)?);
            }
        }
    }
    Ok(dtos)
}

///
/// Deletes the document at the given path.
///
/// ## Arguments
/// * 'auth' The authentication token
/// * 'path' The relative collection path and document id, for example "my_collection/document_id"
/// * 'fail_if_not_existing' If true this method will return an error if the document does not exist.
pub fn delete<'a, BEARER>(
    auth: &'a mut BEARER,
    path: &str,
    fail_if_not_existing: bool,
) -> Result<()>
where
    for<'c> BEARER: FirebaseAuthBearer<'c>,
{
    let url = format!(firebase_url!(), auth.projectid(), path);

    let query_request = dto::Write {
        current_document: Some(dto::Precondition {
            exists: match fail_if_not_existing {
                true => Some(true),
                false => None,
            },
            ..Default::default()
        }),
        ..Default::default()
    };

    let mut resp = Client::new()
        .delete(&url)
        .bearer_auth(auth.bearer().to_owned())
        .json(&query_request)
        .send()?;

    if resp.status() != 200 {
        return Err(FirebaseError::UnexpectedResponse(
            "Firestore delete request failed: ",
            resp.status(),
            resp.text()?,
            serde_json::to_string_pretty(&url)?,
        ));
    }

    Ok({})
}

#[cfg(test)]
mod tests {
    use super::*;

    use super::Result;
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize)]
    struct DemoPod {
        integer_test: u32,
        boolean_test: bool,
        string_test: String,
    }

    #[test]
    fn test_document_to_pod() -> Result<()> {
        let mut map: HashMap<String, dto::Value> = HashMap::new();
        map.insert(
            "integer_test".to_owned(),
            dto::Value {
                integer_value: Some("12".to_owned()),
                ..Default::default()
            },
        );
        map.insert(
            "boolean_test".to_owned(),
            dto::Value {
                boolean_value: Some(true),
                ..Default::default()
            },
        );
        map.insert(
            "string_test".to_owned(),
            dto::Value {
                string_value: Some("abc".to_owned()),
                ..Default::default()
            },
        );
        let t = dto::Document {
            fields: Some(map),
            ..Default::default()
        };
        let firebase_doc: DemoPod = document_to_pod(&t)?;
        assert_eq!(firebase_doc.string_test, "abc");
        assert_eq!(firebase_doc.integer_test, 12);
        assert_eq!(firebase_doc.boolean_test, true);

        Ok(())
    }

    #[test]
    fn test_pod_to_document() -> Result<()> {
        let t = DemoPod {
            integer_test: 12,
            boolean_test: true,
            string_test: "abc".to_owned(),
        };
        let firebase_doc = pod_to_document(&t)?;
        let map = firebase_doc.fields;
        assert_eq!(
            map.unwrap()
                .get("integer_test")
                .expect("a value in the map for integer_test")
                .integer_value
                .as_ref()
                .expect("an integer value"),
            "12"
        );

        Ok(())
    }
}