This commit is contained in:
JMARyA 2024-07-24 15:44:37 +02:00
parent ebefb97d9c
commit 0acc799174
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263
3 changed files with 67 additions and 43 deletions

View file

@ -48,6 +48,31 @@ pub trait Model:
}
}
/// Insert or update an existing `Model`
fn insert_overwrite(
&self,
) -> impl std::future::Future<Output = Result<(), mongodb::error::Error>> + Send
where
Self: Sync,
{
async {
if self.insert().await.is_err() {
let db = get_mongo!();
let collection = col!(db, Self::collection_name());
collection
.update_one(
id_of!(self.id()),
mongodb::bson::doc! {"$set": mongodb::bson::to_document(self).unwrap() },
None,
)
.await?;
}
Ok(())
}
}
/// Remove a `Model` from the database.
#[must_use]
fn remove(
@ -150,15 +175,22 @@ pub trait Model:
}
}
/// Get multiple `Model`s by using a filter from the database
/// Get multiple `Model`s by using a filter from the database. Pass a `limit` parameter to limit the amount of `Model`s returned.
#[must_use]
fn find(
filter: mongodb::bson::Document,
limit: Option<i64>,
) -> impl std::future::Future<Output = Option<Vec<Self>>> {
async move {
let db = get_mongo!();
let collection = col!(db, Self::collection_name());
let mut results = collection.find(filter, None).await.ok()?;
let mut results = collection
.find(
filter,
limit.map(|x| FindOptions::builder().limit(x).build()),
)
.await
.ok()?;
let docs = collect_results!(results);
docs.into_iter()
.map(|x| mongodb::bson::from_document(x).unwrap())
@ -166,11 +198,12 @@ pub trait Model:
}
}
/// Get multiple partial `Model`s by using a filter from the database
/// Get multiple partial `Model`s by using a filter from the database. Pass a `limit` parameter to limit the amount of `Model`s returned.
#[must_use]
fn find_partial(
filter: mongodb::bson::Document,
mut part: serde_json::Value,
limit: Option<i64>,
) -> impl std::future::Future<Output = Option<Vec<Self>>> {
async move {
let db = get_mongo!();
@ -184,6 +217,7 @@ pub trait Model:
Some(
FindOptions::builder()
.projection(Some(mongodb::bson::to_document(&part).unwrap()))
.limit(limit)
.build(),
),
)