fireplace 0.6.2

A client for Firebase that seeks to provide a user-friendly interface to interact with Firestore, Firebase Auth, and similar.
Documentation
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// TODO: Include the limitations described here: https://firebase.google.com/docs/firestore/query-data/queries#query_limitations
// TODO: Add doc comment to each implementor

/*
- [x] < less than
- [x] <= less than or equal to
- [x] == equal to
- [x] > greater than
- [x] >= greater than or equal to
- [x] != not equal to
- [x] array-contains
- [ ] array-contains-any
- [ ] in
- [ ] not-in
*/

use firestore_grpc::v1::{
    Value,
    structured_query::{
        CompositeFilter as GrpcCompositeFilter, FieldFilter as GrpcFieldFilter, FieldReference,
        Filter as GrpcFilter, composite_filter::Operator as CompositeFilterOperator,
        field_filter::Operator as FieldFilterOperator, filter::FilterType as GrpcFilterType,
    },
};
use serde::Serialize;

use crate::error::FirebaseError;

use super::{
    client::FirestoreClient, reference::CollectionReference, serde::serialize_to_value_type,
};

/// Represents a Firestore query operator used to test a field's value against
/// a given filter.
///
/// It will be possible to put any arbitrary struct or value into a query
/// operator (as long as the value satisfies the trait bounds), but you will
/// likely want to stick with primitive types like integers, strings, or lists
/// of the two.
///
/// You will see that many of the implementors of this trait will impose
/// trait bounds on the type parameter `T`. This is only done to help you catch
/// potential logic errors in your program. For example, `LessThan` requires
/// that `T` implements `Ord` - but the value will not actually be compared
/// client-side but only on the server-side by Firestore. Therefore your
/// implementation of `Ord` will not affect the filtering behavior.
///
/// To see which query operators are supported by Firestore, see the [official Firestore documentation](https://firebase.google.com/docs/firestore/query-data/queries#query_operators).
pub trait QueryOperator<T: Serialize> {
    /// Returns the value that the document field will be checked against.
    fn get_value(self) -> T;

    /// Returns the Firestore field filter operator code that represents which
    /// filter operation will be applied to the value by Firestore.
    fn get_operator_code(&self) -> FieldFilterOperator;
}

pub struct GreaterThan<T: Ord + Serialize>(pub T);

impl<T: Ord + Serialize> QueryOperator<T> for GreaterThan<T> {
    fn get_value(self) -> T {
        self.0
    }

    fn get_operator_code(&self) -> FieldFilterOperator {
        FieldFilterOperator::GreaterThan
    }
}

pub struct GreaterThanOrEqual<T: Ord + Serialize>(pub T);

impl<T: Ord + Serialize> QueryOperator<T> for GreaterThanOrEqual<T> {
    fn get_value(self) -> T {
        self.0
    }

    fn get_operator_code(&self) -> FieldFilterOperator {
        FieldFilterOperator::GreaterThanOrEqual
    }
}

pub struct LessThan<T: Ord + Serialize>(pub T);

impl<T: Ord + Serialize> QueryOperator<T> for LessThan<T> {
    fn get_value(self) -> T {
        self.0
    }

    fn get_operator_code(&self) -> FieldFilterOperator {
        FieldFilterOperator::LessThan
    }
}

pub struct LessThanOrEqual<T: Ord + Serialize>(pub T);

impl<T: Ord + Serialize> QueryOperator<T> for LessThanOrEqual<T> {
    fn get_value(self) -> T {
        self.0
    }

    fn get_operator_code(&self) -> FieldFilterOperator {
        FieldFilterOperator::LessThanOrEqual
    }
}

pub struct EqualTo<T: PartialEq + Serialize>(pub T);

impl<T: PartialEq + Serialize> QueryOperator<T> for EqualTo<T> {
    fn get_value(self) -> T {
        self.0
    }

    fn get_operator_code(&self) -> FieldFilterOperator {
        FieldFilterOperator::Equal
    }
}

pub struct NotEqual<T: PartialEq + Serialize>(pub T);

impl<T: PartialEq + Serialize> QueryOperator<T> for NotEqual<T> {
    fn get_value(self) -> T {
        self.0
    }

    fn get_operator_code(&self) -> FieldFilterOperator {
        FieldFilterOperator::NotEqual
    }
}

pub struct ArrayContains<T: Eq + Serialize>(pub T);

impl<T: Eq + Serialize> QueryOperator<T> for ArrayContains<T> {
    fn get_value(self) -> T {
        self.0
    }

    fn get_operator_code(&self) -> FieldFilterOperator {
        FieldFilterOperator::ArrayContains
    }
}

pub fn filter<'a, T: Serialize + 'a + Send>(
    field: impl Into<String> + 'a,
    check_against: impl QueryOperator<T> + 'a,
) -> Filter<'a> {
    let field_filter = create_field_filter(field.into(), check_against);
    Filter::Single(field_filter)
}

pub enum Filter<'a> {
    Composite(Vec<FieldFilter<'a>>),
    Single(FieldFilter<'a>),
}

pub struct FieldFilter<'a> {
    field: String,
    op: FieldFilterOperator,
    value: Box<dyn erased_serde::Serialize + 'a + Send>,
}

impl<'a> Filter<'a> {
    pub fn empty() -> Self {
        Self::Composite(vec![])
    }

    pub fn and<T: Serialize + 'a + Send>(
        self,
        field: impl Into<String> + 'a,
        check_against: impl QueryOperator<T> + 'a,
    ) -> Self {
        let other_field_filter = create_field_filter(field.into(), check_against);

        match self {
            Filter::Composite(mut filters) => {
                filters.push(other_field_filter);
                Filter::Composite(filters)
            }
            Filter::Single(filter) => Filter::Composite(vec![filter, other_field_filter]),
        }
    }

    pub fn combine(self, other: Self) -> Self {
        let (mut filters, other) = match (self, other) {
            (Self::Composite(filters), other) | (other, Self::Composite(filters)) => {
                (filters, other)
            }
            (Self::Single(filter), other) => (vec![filter], other),
        };

        match other {
            Self::Composite(other_filters) => filters.extend(other_filters),
            Self::Single(other_filter) => filters.push(other_filter),
        }

        Self::Composite(filters)
    }
}

fn create_field_filter<'a, T, Q>(field: String, query_op: Q) -> FieldFilter<'a>
where
    T: Serialize + 'a + Send,
    Q: QueryOperator<T> + 'a,
{
    let op = query_op.get_operator_code();
    let value = query_op.get_value();

    FieldFilter {
        field,
        op,
        value: Box::new(value),
    }
}

pub(crate) fn try_into_grpc_filter(
    filter: Filter,
    root_resource_path: &str,
) -> Result<GrpcFilter, FirebaseError> {
    let filter_type = match filter {
        Filter::Single(filter) => {
            GrpcFilterType::FieldFilter(try_into_grpc_field_filter(filter, root_resource_path)?)
        }
        Filter::Composite(filters) => {
            let f = filters
                .into_iter()
                .map(|f| {
                    try_into_grpc_filter_type(f, root_resource_path).map(|ft| GrpcFilter {
                        filter_type: Some(ft),
                    })
                })
                .collect::<Result<Vec<_>, FirebaseError>>()?;
            GrpcFilterType::CompositeFilter(GrpcCompositeFilter {
                op: CompositeFilterOperator::And as i32,
                filters: f,
            })
        }
    };

    Ok(GrpcFilter {
        filter_type: Some(filter_type),
    })
}

fn try_into_grpc_filter_type(
    field_filter: FieldFilter,
    root_resource_path: &str,
) -> Result<GrpcFilterType, FirebaseError> {
    let value = serialize_to_value_type(&field_filter.value, root_resource_path)?;
    let firestore_value = Value {
        value_type: Some(value),
    };

    let filter_type = GrpcFilterType::FieldFilter(GrpcFieldFilter {
        field: Some(firestore_grpc::v1::structured_query::FieldReference {
            field_path: field_filter.field,
        }),
        op: field_filter.op as i32,
        value: Some(firestore_value),
    });

    Ok(filter_type)
}

fn try_into_grpc_field_filter(
    field_filter: FieldFilter,
    root_resource_path: &str,
) -> Result<GrpcFieldFilter, FirebaseError> {
    let value_type = serialize_to_value_type(&field_filter.value, root_resource_path)?;
    let value = Value {
        value_type: Some(value_type),
    };

    let grpc_field_filter = GrpcFieldFilter {
        field: Some(FieldReference {
            field_path: field_filter.field,
        }),
        op: field_filter.op as i32,
        value: Some(value),
    };

    Ok(grpc_field_filter)
}

pub(crate) struct ApiQueryOptions<'a> {
    pub parent: String,
    pub collection_name: String,
    pub filter: Option<Filter<'a>>,
    pub limit: Option<i32>,
    pub offset: Option<i32>,
    /// Whether to search descendant collections with the same name
    pub should_search_descendants: bool,
}

impl<'a> ApiQueryOptions<'a> {
    pub(crate) fn from_query<T>(client: &FirestoreClient, query: T) -> Self
    where
        T: FirestoreQuery<'a>,
    {
        let parent_path = query
            .parent_path()
            .map(|p| client.get_name_with(p))
            .unwrap_or_else(|| client.root_resource_path().to_string());

        Self {
            parent: parent_path,
            collection_name: query.collection_name().to_string(),
            limit: query.limit(),
            offset: query.offset(),
            should_search_descendants: query.should_search_descendants(),
            filter: query.filter(),
        }
    }
}

pub trait FirestoreQuery<'a> {
    fn filter(self) -> Option<Filter<'a>>;
    fn collection_name(&self) -> &str;
    fn parent_path(&self) -> Option<String>;
    fn should_search_descendants(&self) -> bool;
    fn limit(&self) -> Option<i32>;
    fn offset(&self) -> Option<i32>;
}

pub struct CollectionGroupQuery<'a> {
    collection_name: String,
    filter: Option<Filter<'a>>,
    limit: Option<i32>,
    offset: Option<i32>,
}

pub fn collection_group<'a>(collection_name: impl Into<String>) -> CollectionGroupQuery<'a> {
    CollectionGroupQuery::new(collection_name)
}

impl<'a> CollectionGroupQuery<'a> {
    pub fn new(collection_name: impl Into<String>) -> Self {
        CollectionGroupQuery {
            collection_name: collection_name.into(),
            filter: None,
            limit: None,
            offset: None,
        }
    }

    pub fn with_filter(mut self, filter: Filter<'a>) -> Self {
        self.filter = Some(filter);
        self
    }

    pub fn with_limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit as i32);
        self
    }

    pub fn with_offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset as i32);
        self
    }
}

impl<'a> FirestoreQuery<'a> for CollectionGroupQuery<'a> {
    fn filter(self) -> Option<Filter<'a>> {
        self.filter
    }

    fn collection_name(&self) -> &str {
        &self.collection_name
    }

    fn parent_path(&self) -> Option<String> {
        None
    }

    fn should_search_descendants(&self) -> bool {
        true
    }

    fn limit(&self) -> Option<i32> {
        self.limit
    }

    fn offset(&self) -> Option<i32> {
        self.offset
    }
}

impl<'a> FirestoreQuery<'a> for CollectionReference {
    fn filter(self) -> Option<Filter<'a>> {
        None
    }

    fn parent_path(&self) -> Option<String> {
        self.parent().map(|p| p.to_string())
    }

    fn collection_name(&self) -> &str {
        self.name()
    }

    fn should_search_descendants(&self) -> bool {
        false
    }

    fn limit(&self) -> Option<i32> {
        None
    }

    fn offset(&self) -> Option<i32> {
        None
    }
}

pub struct CollectionQuery<'a> {
    collection: CollectionReference,
    filter: Option<Filter<'a>>,
    limit: Option<i32>,
    offset: Option<i32>,
}

impl<'a> CollectionQuery<'a> {
    pub fn new(collection: CollectionReference) -> Self {
        CollectionQuery {
            collection,
            filter: None,
            limit: None,
            offset: None,
        }
    }

    pub fn with_filter(mut self, filter: Filter<'a>) -> Self {
        self.filter = Some(filter);
        self
    }

    pub fn with_limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit as i32);
        self
    }

    pub fn with_offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset as i32);
        self
    }
}

impl<'a> FirestoreQuery<'a> for CollectionQuery<'a> {
    fn filter(self) -> Option<Filter<'a>> {
        self.filter
    }

    fn parent_path(&self) -> Option<String> {
        self.collection.parent_path()
    }

    fn collection_name(&self) -> &str {
        self.collection.collection_name()
    }

    fn should_search_descendants(&self) -> bool {
        self.collection.should_search_descendants()
    }

    fn limit(&self) -> Option<i32> {
        self.limit
    }

    fn offset(&self) -> Option<i32> {
        self.offset
    }
}

#[cfg(test)]
mod tests {
    use firestore_grpc::v1::value::ValueType;

    use crate::firestore::collection;

    use super::*;

    #[test]
    fn combine_operators() {
        let query = filter("age", LessThan(42)).and("name", EqualTo("Bob"));
        let serialized = try_into_grpc_filter(query, "").unwrap();

        let expected = GrpcFilter {
            filter_type: Some(GrpcFilterType::CompositeFilter(GrpcCompositeFilter {
                op: CompositeFilterOperator::And as i32,
                filters: vec![
                    GrpcFilter {
                        filter_type: Some(GrpcFilterType::FieldFilter(GrpcFieldFilter {
                            field: Some(FieldReference {
                                field_path: "age".to_string(),
                            }),
                            op: FieldFilterOperator::LessThan as i32,
                            value: Some(Value {
                                value_type: Some(ValueType::IntegerValue(42)),
                            }),
                        })),
                    },
                    GrpcFilter {
                        filter_type: Some(GrpcFilterType::FieldFilter(GrpcFieldFilter {
                            field: Some(FieldReference {
                                field_path: "name".to_string(),
                            }),
                            op: FieldFilterOperator::Equal as i32,
                            value: Some(Value {
                                value_type: Some(ValueType::StringValue("Bob".to_string())),
                            }),
                        })),
                    },
                ],
            })),
        };

        assert_eq!(serialized, expected);
    }

    #[test]
    fn single_operator() {
        let query = filter("age", EqualTo(collection("users").doc("bob")));
        let serialized = try_into_grpc_filter(query, "prefix").unwrap();

        let expected = GrpcFilter {
            filter_type: Some(GrpcFilterType::FieldFilter(GrpcFieldFilter {
                field: Some(FieldReference {
                    field_path: "age".to_string(),
                }),
                op: FieldFilterOperator::Equal as i32,
                value: Some(Value {
                    value_type: Some(ValueType::ReferenceValue("prefix/users/bob".to_string())),
                }),
            })),
        };

        assert_eq!(serialized, expected);
    }

    #[test]
    fn implements_send() {
        fn assert_send<T: Send>() {}
        assert_send::<super::Filter>();
    }

    #[test]
    fn combine_combines_filters() {
        let a = filter("age", LessThan(42));
        let b = filter("name", EqualTo("Bob"));

        let mut combined = a.combine(b);

        fn extract_inner_filters<'a>(combined: &'a mut Filter) -> &'a Vec<FieldFilter<'a>> {
            if let Filter::Composite(filters) = combined {
                filters.sort_by(|a, b| a.field.cmp(&b.field));
                filters
            } else {
                panic!("Expected combined filter to be a composite filter");
            }
        }

        let filters = extract_inner_filters(&mut combined);
        assert_eq!(filters.len(), 2);
        assert_eq!(filters[0].field, "age");
        assert_eq!(filters[1].field, "name");

        let c = filter("rating", GreaterThan(3));
        let mut combined_again = combined.combine(c);
        let filters = extract_inner_filters(&mut combined_again);

        assert_eq!(filters.len(), 3);
        assert_eq!(filters[0].field, "age");
        assert_eq!(filters[1].field, "name");
        assert_eq!(filters[2].field, "rating");
    }
}