forked from abdolence/firestore-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timestamp.rs
92 lines (77 loc) · 2.79 KB
/
timestamp.rs
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
use chrono::{DateTime, Utc};
use firestore::*;
use serde::{Deserialize, Serialize};
pub fn config_env_var(name: &str) -> Result<String, String> {
std::env::var(name).map_err(|e| format!("{}: {}", name, e))
}
// Example structure to play with
#[derive(Debug, Clone, Deserialize, Serialize)]
struct MyTestStructure {
some_id: String,
// Using a special attribute to indicate timestamp serialization for Firestore
// (for serde_json it will be still the same, usually String serialization, so you can reuse the models)
#[serde(with = "firestore::serialize_as_timestamp")]
created_at: DateTime<Utc>,
// Or you can use a wrapping type
updated_at: Option<FirestoreTimestamp>,
updated_at_always_none: Option<FirestoreTimestamp>,
// Or one more attribute for optionals
#[serde(default)]
#[serde(with = "firestore::serialize_as_optional_timestamp")]
updated_at_attr: Option<DateTime<Utc>>,
#[serde(default)]
#[serde(with = "firestore::serialize_as_optional_timestamp")]
updated_at_attr_always_none: Option<DateTime<Utc>>,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Logging with debug enabled
let subscriber = tracing_subscriber::fmt()
.with_env_filter("firestore=debug")
.finish();
tracing::subscriber::set_global_default(subscriber)?;
// Create an instance
let db = FirestoreDb::new(&config_env_var("PROJECT_ID")?).await?;
const TEST_COLLECTION_NAME: &'static str = "test-ts1";
let my_struct = MyTestStructure {
some_id: "test-1".to_string(),
created_at: Utc::now(),
updated_at: Some(Utc::now().into()),
updated_at_always_none: None,
updated_at_attr: Some(Utc::now().into()),
updated_at_attr_always_none: None,
};
db.fluent()
.delete()
.from(TEST_COLLECTION_NAME)
.document_id(&my_struct.some_id)
.execute()
.await?;
// A fluent version of create document/object
let object_returned: MyTestStructure = db
.fluent()
.insert()
.into(TEST_COLLECTION_NAME)
.document_id(&my_struct.some_id)
.object(&my_struct)
.execute()
.await?;
println!("Created: {:?}", object_returned);
// Query our data
let objects1: Vec<MyTestStructure> = db
.fluent()
.select()
.from(TEST_COLLECTION_NAME)
.filter(|q| {
q.for_all([q
.field(path!(MyTestStructure::created_at))
.less_than_or_equal(
firestore::FirestoreTimestamp(Utc::now()), // Using the wrapping type to indicate serialization without attribute
)])
})
.obj()
.query()
.await?;
println!("Now in the list: {:?}", objects1);
Ok(())
}