From f78cf419fc57e0f48d78b42c1386c1513b50f31c Mon Sep 17 00:00:00 2001 From: JMARyA Date: Mon, 22 Jul 2024 16:22:11 +0200 Subject: [PATCH] update --- Cargo.lock | 1 - Cargo.toml | 4 ++-- src/lib.rs | 16 +++++++++++++--- src/model/reference.rs | 16 +++++++++++----- 4 files changed, 26 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fcb2026..a113675 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1369,7 +1369,6 @@ dependencies = [ "libc", "mio", "num_cpus", - "parking_lot", "pin-project-lite", "signal-hook-registry", "socket2 0.5.7", diff --git a/Cargo.toml b/Cargo.toml index fc083b0..8458d2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,6 @@ mongodb = "2.8.0" regex = "1.10.5" serde = { version = "1.0.195", features = ["derive"] } serde_json = "1.0.111" -tokio = { version = "1.35.1", features = ["full"] } +tokio = { version = "1.35.1", features = ["sync"], default-features = false } uuid = { version = "1.8.0", features = ["v4"] } -mongod_derive = { path = "./mongod_derive" } \ No newline at end of file +mongod_derive = { path = "./mongod_derive" } diff --git a/src/lib.rs b/src/lib.rs index 66d6136..8f787ba 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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 = 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() + } }; } diff --git a/src/model/reference.rs b/src/model/reference.rs index 4074e0b..16d9784 100644 --- a/src/model/reference.rs +++ b/src/model/reference.rs @@ -80,9 +80,15 @@ impl Validate for Reference { } } -impl Into for Reference { - fn into(self) -> serde_json::Value { - serde_json::Value::String(self.0) +impl From for serde_json::Value { + fn from(value: Reference) -> Self { + Self::String(value.0) + } +} + +impl From 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()) }};