use std::marker::PhantomData;
use std::sync::Arc;
use obj_core::{Document, Id, Result};
use crate::asynchronous::db::unblock;
use crate::Db;
#[derive(Debug)]
pub struct AsyncCollection<T> {
db: Arc<Db>,
name: String,
_phantom: PhantomData<fn() -> T>,
}
impl<T> Clone for AsyncCollection<T> {
fn clone(&self) -> Self {
Self {
db: Arc::clone(&self.db),
name: self.name.clone(),
_phantom: PhantomData,
}
}
}
impl<T> AsyncCollection<T>
where
T: Document + Send + 'static,
{
pub(crate) fn lazy(db: Arc<Db>, name: String) -> Self {
Self {
db,
name,
_phantom: PhantomData,
}
}
pub async fn get(&self, id: Id) -> Result<Option<T>> {
let db = Arc::clone(&self.db);
let name = self.name.clone();
unblock(move || db.collection::<T>(name).get(id)).await
}
pub async fn all(&self) -> Result<Vec<(Id, T)>> {
let db = Arc::clone(&self.db);
let name = self.name.clone();
unblock(move || db.collection::<T>(name).all()).await
}
pub async fn count_all(&self) -> Result<u64> {
let db = Arc::clone(&self.db);
let name = self.name.clone();
unblock(move || db.collection::<T>(name).count_all()).await
}
pub async fn find_unique<K>(&self, index_name: &str, key: K) -> Result<Option<T>>
where
K: Into<obj_core::codec::Dynamic> + Send + 'static,
{
let db = Arc::clone(&self.db);
let name = self.name.clone();
let index_name = index_name.to_owned();
unblock(move || db.collection::<T>(name).find_unique(&index_name, key)).await
}
}