Skip to main content

juniper/types/
scalars.rs

1use std::{marker::PhantomData, rc::Rc, thread::JoinHandle};
2
3use derive_more::with_trait::{Deref, Display, From, Into};
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    GraphQLScalar, IntoFieldError, Scalar,
8    ast::{InputValue, Selection, ToInputValue},
9    executor::{ExecutionResult, Executor, Registry},
10    graphql_scalar,
11    macros::reflect,
12    parser::{ParseError, ScalarToken, Token},
13    schema::meta::MetaType,
14    types::{
15        async_await::GraphQLValueAsync,
16        base::{GraphQLType, GraphQLValue},
17        subscriptions::GraphQLSubscriptionValue,
18    },
19    value::{
20        FromScalarValue, ParseScalarResult, ScalarValue, ToScalarValue, TryToPrimitive, Value,
21        WrongInputScalarTypeError,
22    },
23};
24
25/// An ID as defined by the GraphQL specification
26///
27/// Represented as a string, but can be converted _to_ from an integer as well.
28#[derive(
29    Clone, Debug, Deref, Deserialize, Display, Eq, From, GraphQLScalar, Into, PartialEq, Serialize,
30)]
31#[deref(forward)]
32#[from(Box<str>, String)]
33#[into(Box<str>, String)]
34#[graphql(parse_token(String, i32))]
35pub struct ID(Box<str>);
36
37impl ID {
38    fn to_output(&self) -> &str {
39        &self.0
40    }
41
42    fn from_input<S: ScalarValue>(v: &Scalar<S>) -> Result<Self, WrongInputScalarTypeError<'_, S>> {
43        v.try_to_string()
44            .or_else(|| v.try_to_int().as_ref().map(ToString::to_string))
45            .map(|s| Self(s.into()))
46            .ok_or_else(|| WrongInputScalarTypeError {
47                type_name: arcstr::literal!("String` or `Int"),
48                input: &**v,
49            })
50    }
51}
52
53impl ID {
54    /// Construct a new [`ID`] from anything implementing [`Into`]`<`[`String`]`>`.
55    ///
56    /// [`String`]: std::string::String
57    #[must_use]
58    pub fn new<S: Into<String>>(value: S) -> Self {
59        ID(value.into().into())
60    }
61}
62
63#[graphql_scalar]
64#[graphql(
65    with = impl_string_scalar,
66    to_output_with = String::as_str
67    from_input_with = __builtin,
68)]
69type String = std::string::String;
70
71mod impl_string_scalar {
72    use super::*;
73
74    impl<'s, S> FromScalarValue<'s, S> for String
75    where
76        S: TryToPrimitive<'s, Self, Error: IntoFieldError<S>> + 's,
77    {
78        type Error = S::Error;
79
80        fn from_scalar_value(v: &'s S) -> Result<Self, Self::Error> {
81            v.try_to_primitive()
82        }
83    }
84
85    pub(super) fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
86        if let ScalarToken::String(lit) = value {
87            let parsed = lit.parse()?;
88            // TODO: Allow cheaper from `Cow<'_, str>` conversions for `ScalarValue`.
89            Ok(parsed.into_owned().into())
90        } else {
91            Err(ParseError::unexpected_token(Token::Scalar(value)))
92        }
93    }
94}
95
96#[graphql_scalar]
97#[graphql(
98    name = "String", 
99    with = impl_arcstr_scalar,
100    to_output_with = ScalarValue::from_displayable,
101    parse_token(String)
102)]
103type ArcStr = arcstr::ArcStr;
104
105mod impl_arcstr_scalar {
106    use super::ArcStr;
107    use crate::{FromScalarValue, Scalar, ScalarValue};
108
109    pub(super) fn from_input<S: ScalarValue>(
110        v: &Scalar<S>,
111    ) -> Result<ArcStr, <&str as FromScalarValue<'_, S>>::Error> {
112        if let Some(s) = v.downcast_type::<ArcStr>() {
113            Ok(s.clone())
114        } else {
115            v.try_to::<&str>().map(ArcStr::from)
116        }
117    }
118}
119
120#[graphql_scalar]
121#[graphql(
122    name = "String", 
123    with = impl_compactstring_scalar,
124    to_output_with = ScalarValue::from_displayable,
125    parse_token(String),
126)]
127type CompactString = compact_str::CompactString;
128
129mod impl_compactstring_scalar {
130    use super::CompactString;
131    use crate::{FromScalarValue, Scalar, ScalarValue};
132
133    pub(super) fn from_input<S: ScalarValue>(
134        v: &Scalar<S>,
135    ) -> Result<CompactString, <&str as FromScalarValue<'_, S>>::Error> {
136        if let Some(s) = v.downcast_type::<CompactString>() {
137            Ok(s.clone())
138        } else {
139            v.try_to::<&str>().map(CompactString::from)
140        }
141    }
142}
143
144impl<S> reflect::WrappedType<S> for str {
145    const VALUE: reflect::WrappedValue = 1;
146}
147
148impl<S> reflect::BaseType<S> for str {
149    const NAME: reflect::Type = "String";
150}
151
152impl<S> reflect::BaseSubTypes<S> for str {
153    const NAMES: reflect::Types = &[<Self as reflect::BaseType<S>>::NAME];
154}
155
156impl<S> GraphQLType<S> for str
157where
158    S: ScalarValue,
159{
160    fn name(_: &()) -> Option<ArcStr> {
161        Some(arcstr::literal!("String"))
162    }
163
164    fn meta(_: &(), registry: &mut Registry<S>) -> MetaType<S> {
165        registry.build_scalar_type::<String>(&()).into_meta()
166    }
167}
168
169impl<S> GraphQLValue<S> for str
170where
171    S: ScalarValue,
172{
173    type Context = ();
174    type TypeInfo = ();
175
176    fn type_name(&self, info: &Self::TypeInfo) -> Option<ArcStr> {
177        <Self as GraphQLType<S>>::name(info)
178    }
179
180    fn resolve(
181        &self,
182        _: &(),
183        _: Option<&[Selection<S>]>,
184        _: &Executor<Self::Context, S>,
185    ) -> ExecutionResult<S> {
186        Ok(Value::Scalar(self.to_scalar_value()))
187    }
188}
189
190impl<S> GraphQLValueAsync<S> for str
191where
192    S: ScalarValue + Send + Sync,
193{
194    fn resolve_async<'a>(
195        &'a self,
196        info: &'a Self::TypeInfo,
197        selection_set: Option<&'a [Selection<S>]>,
198        executor: &'a Executor<Self::Context, S>,
199    ) -> crate::BoxFuture<'a, ExecutionResult<S>> {
200        use futures::future;
201        Box::pin(future::ready(self.resolve(info, selection_set, executor)))
202    }
203}
204
205impl<'s, S> FromScalarValue<'s, S> for &'s str
206where
207    S: TryToPrimitive<'s, Self, Error: IntoFieldError<S>> + 's,
208{
209    type Error = S::Error;
210
211    fn from_scalar_value(v: &'s S) -> Result<Self, Self::Error> {
212        v.try_to_primitive()
213    }
214}
215
216impl<S: ScalarValue> ToScalarValue<S> for str {
217    fn to_scalar_value(&self) -> S {
218        S::from_displayable(self)
219    }
220}
221
222impl<S> ToInputValue<S> for str
223where
224    Self: ToScalarValue<S>,
225{
226    fn to_input_value(&self) -> InputValue<S> {
227        InputValue::Scalar(self.to_scalar_value())
228    }
229}
230
231#[graphql_scalar]
232#[graphql(with = impl_boolean_scalar, from_input_with = __builtin)]
233type Boolean = bool;
234
235mod impl_boolean_scalar {
236    use super::*;
237
238    impl<'s, S> FromScalarValue<'s, S> for Boolean
239    where
240        S: TryToPrimitive<'s, Self, Error: IntoFieldError<S>> + 's,
241    {
242        type Error = S::Error;
243
244        fn from_scalar_value(v: &'s S) -> Result<Self, Self::Error> {
245            v.try_to_primitive()
246        }
247    }
248
249    pub(super) fn to_output<S: ScalarValue>(v: &Boolean) -> S {
250        (*v).into()
251    }
252
253    pub(super) fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
254        // `Boolean`s are parsed separately, they shouldn't reach this code path.
255        Err(ParseError::unexpected_token(Token::Scalar(value)))
256    }
257}
258
259#[graphql_scalar]
260#[graphql(with = impl_int_scalar, from_input_with = __builtin)]
261type Int = i32;
262
263mod impl_int_scalar {
264    use super::*;
265
266    impl<'s, S> FromScalarValue<'s, S> for Int
267    where
268        S: TryToPrimitive<'s, Self, Error: IntoFieldError<S>> + 's,
269    {
270        type Error = S::Error;
271
272        fn from_scalar_value(v: &'s S) -> Result<Self, Self::Error> {
273            v.try_to_primitive()
274        }
275    }
276
277    pub(super) fn to_output<S: ScalarValue>(v: &Int) -> S {
278        (*v).into()
279    }
280
281    pub(super) fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
282        if let ScalarToken::Int(v) = value {
283            v.parse()
284                .map_err(|_| ParseError::unexpected_token(Token::Scalar(value)))
285                .map(|s: i32| s.into())
286        } else {
287            Err(ParseError::unexpected_token(Token::Scalar(value)))
288        }
289    }
290}
291
292#[graphql_scalar]
293#[graphql(with = impl_float_scalar, from_input_with = __builtin)]
294type Float = f64;
295
296mod impl_float_scalar {
297    use super::*;
298
299    impl<'s, S> FromScalarValue<'s, S> for Float
300    where
301        S: TryToPrimitive<'s, Self, Error: IntoFieldError<S>> + 's,
302    {
303        type Error = S::Error;
304
305        fn from_scalar_value(v: &'s S) -> Result<Self, Self::Error> {
306            v.try_to_primitive()
307        }
308    }
309
310    pub(super) fn to_output<S: ScalarValue>(v: &Float) -> S {
311        (*v).into()
312    }
313
314    pub(super) fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
315        match value {
316            ScalarToken::Int(v) => v
317                .parse()
318                .map_err(|_| ParseError::unexpected_token(Token::Scalar(value)))
319                .map(|s: i32| f64::from(s).into()),
320            ScalarToken::Float(v) => v
321                .parse()
322                .map_err(|_| ParseError::unexpected_token(Token::Scalar(value)))
323                .map(|s: f64| s.into()),
324            ScalarToken::String(_) => Err(ParseError::unexpected_token(Token::Scalar(value))),
325        }
326    }
327}
328
329/// Utility type to define read-only schemas
330///
331/// If you instantiate `RootNode` with this as the mutation, no mutation will be
332/// generated for the schema.
333#[derive(Debug)]
334pub struct EmptyMutation<T: ?Sized = ()>(PhantomData<JoinHandle<Box<T>>>);
335
336// `EmptyMutation` doesn't use `T`, so should be `Send` and `Sync` even when `T` is not.
337crate::sa::assert_impl_all!(EmptyMutation<Rc<String>>: Send, Sync);
338
339impl<T: ?Sized> EmptyMutation<T> {
340    /// Construct a new empty mutation
341    #[inline]
342    pub fn new() -> Self {
343        Self(PhantomData)
344    }
345}
346
347impl<S, T> GraphQLType<S> for EmptyMutation<T>
348where
349    S: ScalarValue,
350{
351    fn name(_: &()) -> Option<ArcStr> {
352        Some(arcstr::literal!("_EmptyMutation"))
353    }
354
355    fn meta(_: &(), registry: &mut Registry<S>) -> MetaType<S> {
356        registry.build_object_type::<Self>(&(), &[]).into_meta()
357    }
358}
359
360impl<S, T> GraphQLValue<S> for EmptyMutation<T>
361where
362    S: ScalarValue,
363{
364    type Context = T;
365    type TypeInfo = ();
366
367    fn type_name(&self, info: &Self::TypeInfo) -> Option<ArcStr> {
368        <Self as GraphQLType<S>>::name(info)
369    }
370}
371
372impl<S, T> GraphQLValueAsync<S> for EmptyMutation<T>
373where
374    Self::TypeInfo: Sync,
375    Self::Context: Sync,
376    S: ScalarValue + Send + Sync,
377{
378}
379
380// Implemented manually to omit redundant `T: Default` trait bound, imposed by
381// `#[derive(Default)]`.
382impl<T> Default for EmptyMutation<T> {
383    fn default() -> Self {
384        Self::new()
385    }
386}
387
388/// Utillity type to define read-only schemas
389///
390/// If you instantiate `RootNode` with this as the subscription,
391/// no subscriptions will be generated for the schema.
392pub struct EmptySubscription<T: ?Sized = ()>(PhantomData<JoinHandle<Box<T>>>);
393
394// `EmptySubscription` doesn't use `T`, so should be `Send` and `Sync` even when `T` is not.
395crate::sa::assert_impl_all!(EmptySubscription<Rc<String>>: Send, Sync);
396
397impl<T: ?Sized> EmptySubscription<T> {
398    /// Construct a new empty subscription
399    #[inline]
400    pub fn new() -> Self {
401        Self(PhantomData)
402    }
403}
404
405impl<S, T> GraphQLType<S> for EmptySubscription<T>
406where
407    S: ScalarValue,
408{
409    fn name(_: &()) -> Option<ArcStr> {
410        Some(arcstr::literal!("_EmptySubscription"))
411    }
412
413    fn meta(_: &(), registry: &mut Registry<S>) -> MetaType<S> {
414        registry.build_object_type::<Self>(&(), &[]).into_meta()
415    }
416}
417
418impl<S, T> GraphQLValue<S> for EmptySubscription<T>
419where
420    S: ScalarValue,
421{
422    type Context = T;
423    type TypeInfo = ();
424
425    fn type_name(&self, info: &Self::TypeInfo) -> Option<ArcStr> {
426        <Self as GraphQLType<S>>::name(info)
427    }
428}
429
430impl<T, S> GraphQLSubscriptionValue<S> for EmptySubscription<T>
431where
432    Self::TypeInfo: Sync,
433    Self::Context: Sync,
434    S: ScalarValue + Send + Sync + 'static,
435{
436}
437
438// Implemented manually to omit redundant `T: Default` trait bound, imposed by
439// `#[derive(Default)]`.
440impl<T> Default for EmptySubscription<T> {
441    fn default() -> Self {
442        Self::new()
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use crate::{
449        parser::{ScalarToken, StringLiteral},
450        value::{DefaultScalarValue, ParseScalarValue, ScalarValue as _},
451    };
452
453    use super::{EmptyMutation, EmptySubscription, ID};
454
455    #[test]
456    fn test_id_from_string() {
457        let actual = ID::from(String::from("foo"));
458        let expected = ID("foo".into());
459        assert_eq!(actual, expected);
460    }
461
462    #[test]
463    fn test_id_new() {
464        let actual = ID::new("foo");
465        let expected = ID("foo".into());
466        assert_eq!(actual, expected);
467    }
468
469    #[test]
470    fn test_id_deref() {
471        let id = ID("foo".into());
472        assert_eq!(id.len(), 3);
473    }
474
475    #[test]
476    fn test_id_display() {
477        let id = ID("foo".into());
478        assert_eq!(id.to_string(), "foo");
479    }
480
481    #[test]
482    fn parse_strings() {
483        for (input, expected) in [
484            (r#""simple""#, "simple"),
485            (r#"" white space ""#, " white space "),
486            (r#""quote \"""#, r#"quote ""#),
487            (r#""escaped \n\r\b\t\f""#, "escaped \n\r\u{0008}\t\u{000c}"),
488            (r#""slashes \\ \/""#, r"slashes \ /"),
489            (
490                r#""unicode \u1234\u5678\u90AB\uCDEF""#,
491                "unicode \u{1234}\u{5678}\u{90ab}\u{cdef}",
492            ),
493            (
494                r#""string with unicode escape outside BMP \u{1F600}""#,
495                "string with unicode escape outside BMP \u{1F600}",
496            ),
497            (
498                r#""string with minimal unicode escape \u{0}""#,
499                "string with minimal unicode escape \u{0}",
500            ),
501            (
502                r#""string with maximal unicode escape \u{10FFFF}""#,
503                "string with maximal unicode escape \u{10FFFF}",
504            ),
505            (
506                r#""string with maximal minimal unicode escape \u{000000}""#,
507                "string with maximal minimal unicode escape \u{000000}",
508            ),
509            (
510                r#""string with unicode surrogate pair escape \uD83D\uDE00""#,
511                "string with unicode surrogate pair escape \u{1f600}",
512            ),
513            (
514                r#""string with minimal surrogate pair escape \uD800\uDC00""#,
515                "string with minimal surrogate pair escape \u{10000}",
516            ),
517            (
518                r#""string with maximal surrogate pair escape \uDBFF\uDFFF""#,
519                "string with maximal surrogate pair escape \u{10FFFF}",
520            ),
521        ] {
522            let res = <String as ParseScalarValue<DefaultScalarValue>>::from_str(
523                ScalarToken::String(StringLiteral::Quoted(input)),
524            );
525            assert!(res.is_ok(), "parsing error occurred: {}", res.unwrap_err());
526
527            let s: Option<String> = res.unwrap().try_to().ok();
528            assert!(s.is_some(), "no string returned");
529            assert_eq!(s.unwrap(), expected);
530        }
531    }
532
533    #[test]
534    fn parse_block_strings() {
535        for (input, expected) in [
536            (r#""""""""#, ""),
537            (r#""""simple""""#, "simple"),
538            (r#"""" white space """"#, " white space "),
539            (r#""""contains " quote""""#, r#"contains " quote"#),
540            (
541                r#""""contains \""" triple quote""""#,
542                r#"contains """ triple quote"#,
543            ),
544            (
545                r#""""contains \"" double quote""""#,
546                r#"contains \"" double quote"#,
547            ),
548            (
549                r#""""contains \\""" triple quote""""#,
550                r#"contains \""" triple quote"#,
551            ),
552            (r#""""\"""quote" """"#, r#""""quote" "#),
553            (r#""""multi\nline""""#, r"multi\nline"),
554            (
555                r#""""multi\rline\r\nnormalized""""#,
556                r"multi\rline\r\nnormalized",
557            ),
558            (
559                r#""""unescaped \\n\\r\\b\\t\\f\\u1234""""#,
560                r"unescaped \\n\\r\\b\\t\\f\\u1234",
561            ),
562            (
563                r#""""unescaped unicode outside BMP \u{1f600}""""#,
564                r"unescaped unicode outside BMP \u{1f600}",
565            ),
566            (r#""""slashes \\\\ \\/""""#, r"slashes \\\\ \\/"),
567            (
568                r#""""
569
570        spans
571          multiple
572            lines
573
574        """"#,
575                "spans\n  multiple\n    lines",
576            ),
577            // removes uniform indentation
578            (
579                r#""""
580    Hello,
581      World!
582
583    Yours,
584      GraphQL.""""#,
585                "Hello,\n  World!\n\nYours,\n  GraphQL.",
586            ),
587            // removes empty leading and trailing lines
588            (
589                r#""""
590
591    Hello,
592      World!
593
594    Yours,
595      GraphQL.
596
597        """"#,
598                "Hello,\n  World!\n\nYours,\n  GraphQL.",
599            ),
600            // retains indentation from first line
601            (
602                r#""""    Hello,
603      World!
604
605    Yours,
606      GraphQL.""""#,
607                "    Hello,\n  World!\n\nYours,\n  GraphQL.",
608            ),
609            // does not alter trailing spaces
610            (
611                r#""""
612    Hello,
613      World!
614
615    Yours,
616      GraphQL.   """"#,
617                "Hello,\n  World!\n\nYours,\n  GraphQL.   ",
618            ),
619        ] {
620            let res = <String as ParseScalarValue<DefaultScalarValue>>::from_str(
621                ScalarToken::String(StringLiteral::Block(input)),
622            );
623            assert!(res.is_ok(), "parsing error occurred: {}", res.unwrap_err());
624
625            let s: Option<String> = res.unwrap().try_to().ok();
626            assert!(s.is_some(), "no string returned");
627            assert_eq!(s.unwrap(), expected);
628        }
629    }
630
631    #[test]
632    fn parse_f64_from_int() {
633        for (v, expected) in [
634            ("0", 0),
635            ("128", 128),
636            ("1601942400", 1601942400),
637            ("1696550400", 1696550400),
638            ("-1", -1),
639        ] {
640            let n = <f64 as ParseScalarValue<DefaultScalarValue>>::from_str(ScalarToken::Int(v));
641            assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err());
642
643            let n: Option<f64> = n.unwrap().try_to().ok();
644            assert!(n.is_some(), "No `f64` returned");
645            assert_eq!(n.unwrap(), f64::from(expected));
646        }
647    }
648
649    #[test]
650    fn parse_f64_from_float() {
651        for (v, expected) in [
652            ("0.", 0.),
653            ("1.2", 1.2),
654            ("1601942400.", 1601942400.),
655            ("1696550400.", 1696550400.),
656            ("-1.2", -1.2),
657        ] {
658            let n = <f64 as ParseScalarValue<DefaultScalarValue>>::from_str(ScalarToken::Float(v));
659            assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err());
660
661            let n: Option<f64> = n.unwrap().try_to().ok();
662            assert!(n.is_some(), "No `f64` returned");
663            assert_eq!(n.unwrap(), expected);
664        }
665    }
666
667    #[test]
668    fn empty_mutation_is_send() {
669        fn check_if_send<T: Send>() {}
670        check_if_send::<EmptyMutation<()>>();
671    }
672
673    #[test]
674    fn empty_subscription_is_send() {
675        fn check_if_send<T: Send>() {}
676        check_if_send::<EmptySubscription<()>>();
677    }
678
679    #[test]
680    fn default_is_invariant_over_type() {
681        struct Bar;
682        let _ = EmptySubscription::<Bar>::default();
683        let _ = EmptyMutation::<Bar>::default();
684    }
685}