1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use std::{
    borrow::Cow,
    ops::{Deref, DerefMut},
};

use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::{
    from_value,
    parser::types::Field,
    registry::{MetaType, MetaTypeId, Registry},
    to_value, ContextSelectionSet, InputType, InputValueResult, OutputType, Positioned,
    ServerResult, Value,
};

/// A scalar that can represent any JSON value.
///
/// If the inner type cannot be serialized as JSON (e.g. it has non-string keys)
/// it will be `null`.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Hash, Default)]
#[serde(transparent)]
pub struct Json<T>(pub T);

impl<T> Deref for Json<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Json<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> From<T> for Json<T> {
    fn from(value: T) -> Self {
        Self(value)
    }
}

impl<T: DeserializeOwned + Serialize + Send + Sync> InputType for Json<T> {
    type RawValueType = T;

    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("JSON")
    }

    fn create_type_info(registry: &mut Registry) -> String {
        registry.create_input_type::<Json<T>, _>(MetaTypeId::Scalar, |_| MetaType::Scalar {
            name: <Self as InputType>::type_name().to_string(),
            description: Some("A scalar that can represent any JSON value.".to_string()),
            is_valid: None,
            visible: None,
            inaccessible: false,
            tags: Default::default(),
            specified_by_url: None,
        })
    }

    fn parse(value: Option<Value>) -> InputValueResult<Self> {
        Ok(from_value(value.unwrap_or_default())?)
    }

    fn to_value(&self) -> Value {
        Value::String(serde_json::to_string(&self.0).unwrap_or_default())
    }

    fn as_raw_value(&self) -> Option<&Self::RawValueType> {
        Some(&self.0)
    }
}

#[async_trait::async_trait]
impl<T: Serialize + Send + Sync> OutputType for Json<T> {
    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("JSON")
    }

    fn create_type_info(registry: &mut Registry) -> String {
        registry.create_output_type::<Json<T>, _>(MetaTypeId::Scalar, |_| MetaType::Scalar {
            name: <Self as OutputType>::type_name().to_string(),
            description: Some("A scalar that can represent any JSON value.".to_string()),
            is_valid: None,
            visible: None,
            inaccessible: false,
            tags: Default::default(),
            specified_by_url: None,
        })
    }

    async fn resolve(
        &self,
        _ctx: &ContextSelectionSet<'_>,
        _field: &Positioned<Field>,
    ) -> ServerResult<Value> {
        Ok(to_value(&self.0).ok().unwrap_or_default())
    }
}

impl InputType for serde_json::Value {
    type RawValueType = serde_json::Value;

    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("JSON")
    }

    fn create_type_info(registry: &mut Registry) -> String {
        registry.create_input_type::<serde_json::Value, _>(MetaTypeId::Scalar, |_| {
            MetaType::Scalar {
                name: <Self as InputType>::type_name().to_string(),
                description: Some("A scalar that can represent any JSON value.".to_string()),
                is_valid: None,
                visible: None,
                inaccessible: false,
                tags: Default::default(),
                specified_by_url: None,
            }
        })
    }

    fn parse(value: Option<Value>) -> InputValueResult<Self> {
        Ok(from_value(value.unwrap_or_default())?)
    }

    fn to_value(&self) -> Value {
        Value::String(self.to_string())
    }

    fn as_raw_value(&self) -> Option<&Self::RawValueType> {
        Some(&self)
    }
}

#[async_trait::async_trait]
impl OutputType for serde_json::Value {
    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("JSON")
    }

    fn create_type_info(registry: &mut Registry) -> String {
        registry.create_output_type::<serde_json::Value, _>(MetaTypeId::Scalar, |_| {
            MetaType::Scalar {
                name: <Self as OutputType>::type_name().to_string(),
                description: Some("A scalar that can represent any JSON value.".to_string()),
                is_valid: None,
                visible: None,
                inaccessible: false,
                tags: Default::default(),
                specified_by_url: None,
            }
        })
    }

    async fn resolve(
        &self,
        _ctx: &ContextSelectionSet<'_>,
        _field: &Positioned<Field>,
    ) -> ServerResult<Value> {
        Ok(to_value(self).ok().unwrap_or_default())
    }
}

#[cfg(test)]
mod test {
    use std::collections::HashMap;

    use serde::{Deserialize, Serialize};

    use crate::*;

    #[tokio::test]
    async fn test_json_type() {
        #[derive(Serialize, Deserialize)]
        struct MyStruct {
            a: i32,
            b: i32,
            c: HashMap<String, i32>,
        }

        struct Query;

        #[Object(internal)]
        impl Query {
            async fn obj(&self, input: Json<MyStruct>) -> Json<MyStruct> {
                input
            }
        }

        let query = r#"{ obj(input: { a: 1, b: 2, c: { a: 11, b: 22 } } ) }"#;
        let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
        assert_eq!(
            schema.execute(query).await.into_result().unwrap().data,
            value!({
             "obj": {
                 "a": 1,
                 "b": 2,
                 "c": { "a": 11, "b": 22 }
             }
            })
        );
    }

    #[tokio::test]
    async fn test_json_type_for_serialize_only() {
        #[derive(Serialize)]
        struct MyStruct {
            a: i32,
            b: i32,
            c: HashMap<String, i32>,
        }

        struct Query;

        #[Object(internal)]
        impl Query {
            async fn obj(&self) -> Json<MyStruct> {
                MyStruct {
                    a: 1,
                    b: 2,
                    c: {
                        let mut values = HashMap::new();
                        values.insert("a".to_string(), 11);
                        values.insert("b".to_string(), 22);
                        values
                    },
                }
                .into()
            }
        }

        let query = r#"{ obj }"#;
        let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
        assert_eq!(
            schema.execute(query).await.into_result().unwrap().data,
            value!({
             "obj": {
                 "a": 1,
                 "b": 2,
                 "c": { "a": 11, "b": 22 }
             }
            })
        );
    }
}