Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add integration for serde_json::Value #325

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ your Schemas automatically.
- [uuid][uuid]
- [url][url]
- [chrono][chrono]
- [serde_json][serde_json]

### Web Frameworks

Expand Down Expand Up @@ -101,3 +102,4 @@ Juniper has not reached 1.0 yet, thus some API instability should be expected.
[uuid]: https://crates.io/crates/uuid
[url]: https://crates.io/crates/url
[chrono]: https://crates.io/crates/chrono
[serde_json]: https://crates.io/crates/serde_json
5 changes: 5 additions & 0 deletions juniper/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
The DirectiveLocation::InlineFragment had an invalid literal value,
which broke third party tools like apollo cli.
- Added GraphQL Playground integration
- Added built-in integration for [`serde_json::Value`](https://docs.serde.rs/serde_json/value).
`serde_json::Value` will serialize and deserialize as a
GraphQL scalar `String` named `JsonString`, as GraphQL [does not
support a Map type](https://github.com/facebook/graphql/issues/101).
The integration can be controlled via the `json` feature.

# [0.11.1] 2018-12-19

Expand Down
2 changes: 2 additions & 0 deletions juniper/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ path = "benches/bench.rs"
[features]
nightly = []
expose-test-schema = []
json = ["serde_json"]
default = [
"chrono",
"json",
"url",
"uuid",
]
Expand Down
106 changes: 106 additions & 0 deletions juniper/src/integrations/json.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
use serde_json::Value as JsonValue;

use parser::{ParseError, ScalarToken, Token};
use value::ParseScalarResult;
use Value;

graphql_scalar!(JsonValue as "JsonString" where Scalar = <S> {
description: "JSON serialized as a string"
Comment on lines +7 to +8
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
graphql_scalar!(JsonValue as "JsonString" where Scalar = <S> {
description: "JSON serialized as a string"
#[juniper::graphql_scalar(name = "JsonString", description = "JSON serialized as a string")]
impl<S> GraphQLScalar for GraphQLMap
where
S: juniper::ScalarValue,
{

It seems the macro graphql_scalar! is deprecated, now the #[graphql_scalar] should be used


resolve(&self) -> Value {
Value::scalar(self.to_string())
}

from_input_value(v: &InputValue) -> Option<JsonValue> {
v.as_scalar_value::<String>()
.and_then(|s| serde_json::from_str(s).ok())
}

from_str<'a>(value: ScalarToken<'a>) -> ParseScalarResult<'a, S> {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My custom scalar implementation that worked with JSON objects looked like this:

from_str<'a>(value: ScalarToken<'a>) -> ParseScalarResult<'a, S> {
    <String as ParseScalarValue<S>>::from_str(value)
}

Otherwise, it looks pretty much exactly the same. I don't understand the intricacies of graphql_scalar! so I am not sure that is the correct way to do it...

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just tested this change and it is working for me.

if let ScalarToken::String(value) = value {
Ok(S::from(value.to_owned()))
} else {
Err(ParseError::UnexpectedToken(Token::Scalar(value)))
}
}
});

#[cfg(test)]
mod test {
use super::*;

#[test]
fn json_from_input_value() {
let raw = r#"{ "foo": "bar"}"#;
let input: ::InputValue = ::InputValue::scalar(raw.to_string());

let parsed: JsonValue = ::FromInputValue::from_input_value(&input).unwrap();
let expected: JsonValue = serde_json::from_str(raw).unwrap();

assert_eq!(parsed, expected);
}

}

#[cfg(test)]
mod integration_test {
use super::*;

use executor::Variables;
use schema::model::RootNode;
use types::scalars::EmptyMutation;
use value::Value;

#[test]
fn test_json_serialization() {
let example_raw: JsonValue = serde_json::from_str(
r#"{
"x": 2,
"y": 42
}
"#,
)
.unwrap();
let example_raw = example_raw.to_string();

struct Root;
graphql_object!(Root: () |&self| {
field example_json() -> JsonValue {
serde_json::from_str(r#"{
"x": 2,
"y": 42
}
"#).unwrap()
}
field input_json(input: JsonValue) -> bool {
input.is_array()
}
});

let doc = r#"
{
exampleJson,
inputJson(input: "[]"),
}
"#;

let schema = RootNode::new(Root, EmptyMutation::<()>::new());

let (result, errs) =
::execute(doc, None, &schema, &Variables::new(), &()).expect("Execution failed");

assert_eq!(errs, []);

assert_eq!(
result,
Value::object(
vec![
("exampleJson", Value::scalar(example_raw)),
("inputJson", Value::scalar(true)),
]
.into_iter()
.collect()
)
);
}
}
4 changes: 4 additions & 0 deletions juniper/src/integrations/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ pub mod serde;
/// GraphQL support for [chrono](https://github.com/chronotope/chrono) types.
pub mod chrono;

#[cfg(feature = "json")]
/// GraphQL support for [serde_json::Value](https://docs.serde.rs/serde_json/value/enum.Value.html) types.
pub mod json;

#[cfg(feature = "url")]
/// GraphQL support for [url](https://github.com/servo/rust-url) types.
pub mod url;
Expand Down
2 changes: 1 addition & 1 deletion juniper/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ pub extern crate serde;
#[macro_use]
extern crate serde_derive;

#[cfg(any(test, feature = "expose-test-schema"))]
#[cfg(any(test, feature = "json", feature = "expose-test-schema"))]
extern crate serde_json;

extern crate fnv;
Expand Down