This commit is contained in:
JMARyA 2024-07-22 16:22:11 +02:00
parent 6be8a879f9
commit f78cf419fc
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263
4 changed files with 26 additions and 11 deletions

View file

@ -6,13 +6,23 @@ pub use model::Model;
pub use mongod_derive as derive;
pub use mongodb;
use tokio::sync::OnceCell;
pub static MONGO_CLIENT: OnceCell<mongodb::Client> = OnceCell::const_new();
/// Get a `MongoDB` Client from the environment
#[macro_export]
macro_rules! get_mongo {
() => {
mongodb::Client::with_uri_str(std::env::var("DB_URI").unwrap())
.await
.unwrap()
if let Some(client) = crate::MONGO_CLIENT.get() {
client
} else {
let client = mongodb::Client::with_uri_str(&std::env::var("DB_URI").unwrap())
.await
.unwrap();
crate::MONGO_CLIENT.set(client).unwrap();
crate::MONGO_CLIENT.get().unwrap()
}
};
}

View file

@ -80,9 +80,15 @@ impl Validate for Reference {
}
}
impl Into<serde_json::Value> for Reference {
fn into(self) -> serde_json::Value {
serde_json::Value::String(self.0)
impl From<Reference> for serde_json::Value {
fn from(value: Reference) -> Self {
Self::String(value.0)
}
}
impl From<Reference> for mongodb::bson::Bson {
fn from(value: Reference) -> Self {
mongodb::bson::to_bson(&value.0).unwrap()
}
}
@ -112,12 +118,12 @@ pub trait Referencable {
#[macro_export]
macro_rules! reference_of {
($model:ident, $id:ident) => {{
$model::get_partial($id, &serde_json::json!({}))
$model::get_partial($id, serde_json::json!({}))
.await
.map(|x| x.reference())
}};
($model:ident, $id:literal) => {{
$model::get_partial($id, &serde_json::json!({}))
$model::get_partial($id, serde_json::json!({}))
.await
.map(|x| x.reference())
}};