Change with_setting to accept any JSON value

This commit is contained in:
Tim Maddison 2021-07-23 09:44:04 +01:00
parent b138c757b6
commit fa218b435e

View File

@ -1,5 +1,6 @@
use std::collections::HashMap;
use crate::Value;
use serde::Serialize;
/// Generate the page for GraphQL Playground
@ -564,7 +565,7 @@ pub struct GraphQLPlaygroundConfig<'a> {
endpoint: &'a str,
subscription_endpoint: Option<&'a str>,
headers: Option<HashMap<&'a str, &'a str>>,
settings: Option<HashMap<&'a str, &'a str>>,
settings: Option<HashMap<&'a str, Value>>,
}
impl<'a> GraphQLPlaygroundConfig<'a> {
@ -597,7 +598,17 @@ impl<'a> GraphQLPlaygroundConfig<'a> {
}
/// Set Playground setting for per query.
pub fn with_setting(mut self, name: &'a str, value: &'a str) -> Self {
///
/// ```
/// # use async_graphql::Value;
/// # use async_graphql::http::GraphQLPlaygroundConfig;
/// GraphQLPlaygroundConfig::new("/api/graphql")
/// .with_setting("setting", false)
/// .with_setting("other", Value::Null);
/// ```
pub fn with_setting(mut self, name: &'a str, value: impl Into<Value>) -> Self {
let value = value.into();
if let Some(settings) = &mut self.settings {
settings.insert(name, value);
} else {
@ -608,3 +619,30 @@ impl<'a> GraphQLPlaygroundConfig<'a> {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn test_with_setting_can_use_any_json_value() {
let settings = GraphQLPlaygroundConfig::new("")
.with_setting("string", "string")
.with_setting("bool", false)
.with_setting("number", 10)
.with_setting("null", Value::Null)
.with_setting("array", Vec::from([1,2,3]))
.with_setting("object", BTreeMap::new());
let json = serde_json::to_value(settings).unwrap();
let settings = json["settings"].as_object().unwrap();
assert!(settings["string"].as_str().is_some());
assert!(settings["bool"].as_bool().is_some());
assert!(settings["number"].as_u64().is_some());
assert!(settings["null"].as_null().is_some());
assert!(settings["array"].as_array().is_some());
assert!(settings["object"].as_object().is_some());
}
}