From a8a0984bf5469bae05475ba35ff79d480fd1bd37 Mon Sep 17 00:00:00 2001 From: iancormac84 Date: Fri, 20 Mar 2020 14:03:41 -0400 Subject: [PATCH] Add support for bson crate's ObjectId as a Scalar, so that GraphQL integration with MongoDB become's possible. --- Cargo.toml | 3 ++- README.md | 1 + src/scalars/bson.rs | 21 +++++++++++++++++++++ src/scalars/mod.rs | 9 +++++++++ 4 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 src/scalars/bson.rs diff --git a/Cargo.toml b/Cargo.toml index 742b7903..997f6d42 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ categories = ["network-programming", "asynchronous"] readme = "README.md" [features] -default = ["chrono", "uuid", "url"] +default = ["bson", "chrono", "uuid", "url"] [dependencies] async-graphql-derive = { path = "async-graphql-derive", version = "1.3.2" } @@ -30,6 +30,7 @@ bytes = "0.5.4" Inflector = "0.11.4" base64 = "0.12.0" byteorder = "1.3.4" +bson = { version = "0.14.1", optional = true } chrono = { version = "0.4.10", optional = true } uuid = { version = "0.8.1", optional = true } url = { version = "2.1.1", optional = true } diff --git a/README.md b/README.md index 0012bf3f..f9f78b7a 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ Open `http://localhost:8000` in browser - [X] DateTime - [X] UUID - [X] Url + - [X] ObjectId - [X] Containers - [X] List - [X] Non-Null diff --git a/src/scalars/bson.rs b/src/scalars/bson.rs new file mode 100644 index 00000000..b0c0cde8 --- /dev/null +++ b/src/scalars/bson.rs @@ -0,0 +1,21 @@ +use crate::{impl_scalar_internal, Scalar, Result, Value}; +use bson::oid::ObjectId; + +impl Scalar for ObjectId { + fn type_name() -> &'static str { + "ObjectId" + } + + fn parse(value: &Value) -> Option { + match value { + Value::String(s) => Some(ObjectId::with_string(&s).ok()?), + _ => None, + } + } + + fn to_json(&self) -> Result { + Ok(self.to_string().into()) + } +} + +impl_scalar_internal!(ObjectId); diff --git a/src/scalars/mod.rs b/src/scalars/mod.rs index f1c152a1..d3b294ef 100644 --- a/src/scalars/mod.rs +++ b/src/scalars/mod.rs @@ -9,6 +9,8 @@ mod url; mod datetime; #[cfg(feature = "uuid")] mod uuid; +#[cfg(feature = "bson")] +mod bson; pub use id::ID; @@ -18,6 +20,7 @@ mod tests { use crate::Type; use chrono::{DateTime, Utc}; use uuid::Uuid; + use bson::oid::ObjectId; #[test] fn test_scalar_type() { @@ -53,5 +56,11 @@ mod tests { assert_eq!(::type_name(), "UUID"); assert_eq!(::qualified_type_name(), "UUID!"); } + + #[cfg(feature = "bson")] + { + assert_eq!(::type_name(), "ObjectId"); + assert_eq!(::qualified_type_name(), "ObjectId!"); + } } }