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
use crate::storage::{error::StorageError, Data, DataCollection, DataStorer};
use async_trait::async_trait;
use futures::StreamExt;
use mongodb::{bson, options::ClientOptions, options::FindOneOptions, Client, Database};
#[derive(Clone)]
pub struct MongoDataStorer {
url: String,
db_name: String,
client: Client,
db: Database,
}
impl MongoDataStorer {
pub async fn new(url: &str, db_name: &str) -> Self {
let db_client_options = ClientOptions::parse_with_resolver_config(
url,
mongodb::options::ResolverConfig::cloudflare(),
)
.await
.unwrap();
let client = Client::with_options(db_client_options).unwrap();
let db = client.database(db_name);
MongoDataStorer {
url: url.to_owned(),
db_name: db_name.to_owned(),
client,
db,
}
}
}
#[async_trait]
impl DataStorer for MongoDataStorer {
async fn get(&self, path: &str) -> Result<Data, StorageError> {
let filter_options = FindOneOptions::builder().build();
let filter = bson::doc! { "path": path };
match self
.db
.collection_with_type::<Data>("data")
.find_one(filter, filter_options)
.await
{
Ok(Some(data)) => Ok(data),
Ok(None) => Err(StorageError::NotFound),
Err(e) => Err(StorageError::InternalError {
source: Box::new(e),
}),
}
}
async fn get_collection(
&self,
path: &str,
skip: i64,
page_size: i64,
) -> Result<DataCollection, StorageError> {
let filter_options = mongodb::options::FindOptions::builder()
.skip(skip)
.limit(page_size)
.build();
let filter = bson::doc! { "path": path };
match self
.db
.collection_with_type::<Data>("data")
.find(filter, filter_options)
.await
{
Ok(mut cursor) => {
let mut data = Vec::new();
while let Some(item) = cursor.next().await {
data.push(item.unwrap());
}
Ok(DataCollection { data })
}
Err(e) => Err(StorageError::InternalError {
source: Box::new(e),
}),
}
}
async fn create(&self, data: Data) -> Result<bool, StorageError> {
let filter_options = mongodb::options::ReplaceOptions::builder()
.upsert(true)
.build();
let filter = bson::doc! { "path": data.path() };
match self
.db
.collection_with_type::<Data>("data")
.replace_one(filter, data, filter_options)
.await
{
Ok(_) => Ok(true),
Err(e) => Err(StorageError::InternalError {
source: Box::new(e),
}),
}
}
}