use super::document_reference::DocumentReference;
use super::field_value::MapValue;
use super::query::{Query, QueryState};
use crate::error::FirebaseError;
use crate::firestore::firestore::FirestoreInner;
#[derive(Clone)]
pub struct CollectionReference {
pub(crate) state: QueryState,
}
impl CollectionReference {
pub(crate) fn new(path: impl Into<String>, firestore: std::sync::Arc<FirestoreInner>) -> Self {
Self {
state: QueryState::new(path.into(), firestore),
}
}
pub fn id(&self) -> &str {
self.state.collection_path.rsplit('/').next().unwrap_or(&self.state.collection_path)
}
pub fn document(&self, document_id: impl AsRef<str>) -> DocumentReference {
let path = format!("{}/{}", self.state.collection_path, document_id.as_ref());
DocumentReference::new(path, std::sync::Arc::clone(&self.state.firestore))
}
pub async fn add(&self, data: MapValue) -> Result<DocumentReference, FirebaseError> {
use rand::Rng;
let auto_id: String = rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(20)
.map(char::from)
.collect();
let doc_ref = self.document(&auto_id);
doc_ref.set(data).await?;
Ok(doc_ref)
}
}
#[allow(private_interfaces)]
impl Query for CollectionReference {
fn query_state(&self) -> &QueryState {
&self.state
}
fn with_state(&self, state: QueryState) -> Self {
Self { state }
}
}