use async_trait::async_trait;
use crate::Collection;
use mongodb::bson::{doc, Document};
use mongodb::options::FindOptions;
use super::utils::parse_object_id;
use super::models::{PaginatedQuery, PaginatedData, SortOrder};
#[async_trait]
pub trait CollectionRepository: Collection + Clone + Send + Sync + Unpin
where
Self: serde::Serialize + for<'de> serde::Deserialize<'de>,
{
async fn create(
db: &mongodb::Database,
document: &Self,
) -> Result<Self, mongodb::error::Error> {
let collection = Self::collection(db);
collection.insert_one(document).await?;
Ok(document.clone())
}
async fn create_many(
db: &mongodb::Database,
documents: Vec<Self>,
) -> Result<Vec<Self>, mongodb::error::Error> {
let collection = Self::collection(db);
collection.insert_many(&documents).await?;
Ok(documents)
}
async fn find_by_id(
db: &mongodb::Database,
id: &str,
) -> Result<Option<Self>, mongodb::error::Error> {
let collection = Self::collection(db);
let oid = parse_object_id(id)?;
collection.find_one(doc! { "_id": oid }).await
}
async fn find_one(
db: &mongodb::Database,
filter: Document,
) -> Result<Option<Self>, mongodb::error::Error> {
let collection = Self::collection(db);
collection.find_one(filter).await
}
async fn find_many(
db: &mongodb::Database,
filter: Document,
options: Option<FindOptions>,
) -> Result<Vec<Self>, mongodb::error::Error> {
let collection = Self::collection(db);
let mut cursor = match options {
None => collection.find(filter).await?,
Some(options) => collection.find(filter).with_options(options).await?
};
let mut results = Vec::new();
use futures::TryStreamExt;
while let Some(doc) = cursor.try_next().await? {
results.push(doc);
}
Ok(results)
}
async fn find_all(
db: &mongodb::Database,
) -> Result<Vec<Self>, mongodb::error::Error> {
Self::find_many(db, doc! {}, None).await
}
async fn find_paginated(
db: &mongodb::Database,
filter: Document,
query: &PaginatedQuery,
) -> Result<PaginatedData<Self>, mongodb::error::Error> {
let collection = Self::collection(db);
let total_count = collection.count_documents(filter.clone()).await?;
let sort_doc = if let Some(ref sort_by) = query.sort_by {
let sort_value = match query.sort_order {
SortOrder::Asc => 1,
SortOrder::Desc => -1,
};
doc! { sort_by: sort_value }
} else {
doc! { "_id": -1 } };
let find_options = FindOptions::builder()
.skip(query.skip())
.limit(query.limit())
.sort(sort_doc)
.build();
let items = Self::find_many(db, filter, Some(find_options)).await?;
let total_pages = (total_count as f64 / query.page_size as f64).ceil() as u64;
Ok(PaginatedData {
items,
total_count,
page: query.page,
page_size: query.page_size,
total_pages,
})
}
async fn count(
db: &mongodb::Database,
filter: Document,
) -> Result<u64, mongodb::error::Error> {
let collection = Self::collection(db);
collection.count_documents(filter).await
}
async fn exists(
db: &mongodb::Database,
filter: Document,
) -> Result<bool, mongodb::error::Error> {
Ok(Self::find_one(db, filter).await?.is_some())
}
async fn update_by_id(
db: &mongodb::Database,
id: &str,
update: Document,
) -> Result<bool, mongodb::error::Error> {
let collection = Self::collection(db);
let oid = parse_object_id(id)?;
let result = collection
.update_one(doc! { "_id": oid }, update)
.await?;
Ok(result.modified_count > 0)
}
async fn update_one(
db: &mongodb::Database,
filter: Document,
update: Document,
) -> Result<bool, mongodb::error::Error> {
let collection = Self::collection(db);
let result = collection.update_one(filter, update).await?;
Ok(result.modified_count > 0)
}
async fn update_many(
db: &mongodb::Database,
filter: Document,
update: Document,
) -> Result<u64, mongodb::error::Error> {
let collection = Self::collection(db);
let result = collection.update_many(filter, update).await?;
Ok(result.modified_count)
}
async fn find_one_and_update(
db: &mongodb::Database,
filter: Document,
update: Document,
) -> Result<Option<Self>, mongodb::error::Error> {
let collection = Self::collection(db);
collection.find_one_and_update(filter, update).await
}
async fn delete_by_id(
db: &mongodb::Database,
id: &str,
) -> Result<bool, mongodb::error::Error> {
let collection = Self::collection(db);
let oid = parse_object_id(id)?;
let result = collection.delete_one(doc! { "_id": oid }).await?;
Ok(result.deleted_count > 0)
}
async fn delete_one(
db: &mongodb::Database,
filter: Document,
) -> Result<bool, mongodb::error::Error> {
let collection = Self::collection(db);
let result = collection.delete_one(filter).await?;
Ok(result.deleted_count > 0)
}
async fn delete_many(
db: &mongodb::Database,
filter: Document,
) -> Result<u64, mongodb::error::Error> {
let collection = Self::collection(db);
let result = collection.delete_many(filter).await?;
Ok(result.deleted_count)
}
async fn find_one_and_delete(
db: &mongodb::Database,
filter: Document,
) -> Result<Option<Self>, mongodb::error::Error> {
let collection = Self::collection(db);
collection.find_one_and_delete(filter).await
}
}