use bson::Document;
use crate::error::Error;
pub trait Collection {
const COLLECTION: &'static str;
fn from_document(document: Document) -> Result<Self, Error>
where
Self: Sized;
fn into_document(self) -> Result<Document, Error>;
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bson::{self, Document};
use crate::Error as MongoError;
struct User {
name: String,
}
impl Collection for User {
const COLLECTION: &'static str = "users";
fn from_document(document: Document) -> Result<Self, MongoError> {
let mut document = document;
let mut name: Option<String> = None;
if let Some(value) = document.remove("name") {
name = bson::from_bson(value).map_err(MongoError::invalid_document)?;
}
if name.is_none() {
return Err(MongoError::invalid_document("missing required fields"));
}
Ok(User {
name: name.expect("could not get name"),
})
}
fn into_document(self) -> Result<Document, Error> {
let mut doc = Document::new();
doc.insert("name", self.name);
Ok(doc)
}
}
#[test]
fn collection() {
assert_eq!(User::COLLECTION, "users");
}
#[test]
fn document_to_bson() {
let user = User {
name: "foo".to_owned(),
};
let doc = user.into_document().unwrap();
assert_eq!(doc.get("name").unwrap().as_str().unwrap(), "foo".to_owned());
}
#[test]
fn bson_to_document() {
let mut doc = Document::new();
doc.insert("name", "foo".to_owned());
let user = User::from_document(doc).unwrap();
assert_eq!(user.name, "foo".to_owned());
}
}