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

1
Cargo.lock generated
View file

@ -1369,7 +1369,6 @@ dependencies = [
"libc",
"mio",
"num_cpus",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2 0.5.7",

View file

@ -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" }
mongod_derive = { path = "./mongod_derive" }

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())
}};