Skip to main content

juniper/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![cfg_attr(any(doc, test), doc = include_str!("../README.md"))]
3#![cfg_attr(not(any(doc, test)), doc = env!("CARGO_PKG_NAME"))]
4// Due to `schema_introspection` test.
5#![cfg_attr(test, recursion_limit = "256")]
6
7// Required for using `juniper_codegen` macros inside this crate to resolve
8// absolute `::juniper` path correctly, without errors.
9extern crate core;
10extern crate self as juniper;
11
12#[cfg(test)]
13mod for_benches_only {
14    use bencher as _;
15}
16#[cfg(test)]
17mod for_feature_gated_tests_only {
18    #[cfg(not(feature = "chrono"))]
19    use chrono as _;
20    #[cfg(not(feature = "jiff"))]
21    use jiff as _;
22    #[cfg(not(feature = "anyhow"))]
23    use serial_test as _;
24}
25
26// These are required by the code generated via the `juniper_codegen` macros.
27#[doc(hidden)]
28pub use {async_trait::async_trait, futures, serde, static_assertions as sa};
29
30#[doc(inline)]
31pub use futures::future::{BoxFuture, LocalBoxFuture};
32
33pub use arcstr::{self, ArcStr};
34
35// Depend on juniper_codegen and re-export everything in it.
36// This allows users to just depend on juniper and get the derive
37// functionality automatically.
38pub use juniper_codegen::{
39    GraphQLEnum, GraphQLInputObject, GraphQLInterface, GraphQLObject, GraphQLScalar, GraphQLUnion,
40    graphql_interface, graphql_object, graphql_scalar, graphql_subscription, graphql_union,
41};
42
43#[doc(hidden)]
44#[macro_use]
45pub mod macros;
46mod ast;
47pub mod executor;
48#[cfg(test)]
49pub(crate) mod graphql;
50mod introspection;
51pub mod parser;
52pub(crate) mod schema;
53mod types;
54mod util;
55pub mod validation;
56mod value;
57// This needs to be public until docs have support for private modules:
58// https://github.com/rust-lang/cargo/issues/1520
59pub mod http;
60pub mod integrations;
61
62#[cfg(all(test, not(feature = "expose-test-schema")))]
63mod tests;
64#[cfg(feature = "expose-test-schema")]
65pub mod tests;
66
67#[cfg(test)]
68mod executor_tests;
69
70use derive_more::with_trait::{Display, From};
71use itertools::Itertools as _;
72
73// Needs to be public because macros use it.
74pub use crate::util::to_camel_case;
75
76use crate::introspection::{INTROSPECTION_QUERY, INTROSPECTION_QUERY_WITHOUT_DESCRIPTIONS};
77
78pub use crate::{
79    ast::{
80        Definition, Document, FromInputValue, InputValue, IntoInputValue, Operation, OperationType,
81        Selection, ToInputValue, Type,
82    },
83    executor::{
84        Applies, Context, ExecutionError, ExecutionResult, Executor, FieldError, FieldResult,
85        FromContext, IntoFieldError, IntoResolvable, LookAheadArgument, LookAheadChildren,
86        LookAheadList, LookAheadObject, LookAheadSelection, LookAheadValue, OwnedExecutor,
87        Registry, ValidatedOperation, ValuesStream, Variables,
88    },
89    introspection::IntrospectionFormat,
90    macros::helper::subscription::{ExtractTypeFromStream, IntoFieldResult},
91    parser::{ParseError, ScalarToken, Span, Spanning, StringLiteral},
92    schema::{
93        meta,
94        model::{RootNode, SchemaType},
95    },
96    types::{
97        async_await::{GraphQLTypeAsync, GraphQLValueAsync},
98        base::{Arguments, GraphQLType, GraphQLValue, TypeKind},
99        marker::{self, GraphQLInterface, GraphQLObject, GraphQLUnion},
100        nullable::Nullable,
101        scalars::{EmptyMutation, EmptySubscription, ID},
102        subscriptions::{
103            ExecutionOutput, GraphQLSubscriptionType, GraphQLSubscriptionValue,
104            SubscriptionConnection, SubscriptionCoordinator,
105        },
106    },
107    validation::RuleError,
108    value::{
109        AnyExt, DefaultScalarValue, FromScalarValue, IntoValue, Object, ParseScalarResult,
110        ParseScalarValue, Scalar, ScalarValue, ToScalarValue, TryToPrimitive, Value,
111        WrongInputScalarTypeError,
112    },
113};
114
115/// An error that prevented query execution
116#[expect(missing_docs, reason = "self-explanatory")]
117#[derive(Clone, Debug, Display, Eq, From, PartialEq)]
118pub enum GraphQLError {
119    ParseError(Spanning<ParseError>),
120    #[display("{}", _0.iter().format("\n"))]
121    ValidationError(Vec<RuleError>),
122    #[display("No operation provided")]
123    NoOperationProvided,
124    #[display("Multiple operations provided")]
125    MultipleOperationsProvided,
126    #[display("Unknown operation name")]
127    UnknownOperationName,
128    #[display("Operation is a subscription")]
129    IsSubscription,
130    #[display("Operation is not a subscription")]
131    NotSubscription,
132    /// The requested operation type has no corresponding root type defined in
133    /// the schema — e.g. a `mutation` against [`EmptyMutation`], or a
134    /// `subscription` against [`EmptySubscription`].
135    ///
136    /// [`EmptyMutation`]: crate::EmptyMutation
137    /// [`EmptySubscription`]: crate::EmptySubscription
138    #[display("Schema is not configured for {} operations", match _0 {
139        OperationType::Query => "queries",
140        OperationType::Mutation => "mutations",
141        OperationType::Subscription => "subscriptions",
142    })]
143    NotSupported(OperationType),
144}
145
146impl From<RuleError> for GraphQLError {
147    fn from(value: RuleError) -> Self {
148        vec![value].into()
149    }
150}
151
152impl std::error::Error for GraphQLError {
153    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
154        match self {
155            Self::ParseError(e) => Some(e),
156            Self::ValidationError(errs) => Some(errs.first()?),
157            Self::NoOperationProvided
158            | Self::MultipleOperationsProvided
159            | Self::UnknownOperationName
160            | Self::IsSubscription
161            | Self::NotSubscription
162            | Self::NotSupported(_) => None,
163        }
164    }
165}
166
167/// Executes a query synchronously in the provided schema.
168///
169/// Parses and validates the document with [`ValidatedOperation::new()`] and executes the
170/// operation with [`ValidatedOperation::execute_sync()`].
171pub fn execute_sync<'a, S, QueryT, MutationT, SubscriptionT>(
172    document_source: &'a str,
173    operation_name: Option<&str>,
174    root_node: &'a RootNode<QueryT, MutationT, SubscriptionT, S>,
175    variables: &Variables<S>,
176    context: &QueryT::Context,
177) -> Result<(Value<S>, Vec<ExecutionError<S>>), GraphQLError>
178where
179    S: ScalarValue,
180    QueryT: GraphQLType<S>,
181    MutationT: GraphQLType<S, Context = QueryT::Context>,
182    SubscriptionT: GraphQLType<S, Context = QueryT::Context>,
183{
184    ValidatedOperation::new(document_source, operation_name, root_node)?
185        .execute_sync(variables, context)
186}
187
188/// Executes a query asynchronously in the provided schema.
189///
190/// Parses and validates the document with [`ValidatedOperation::new()`] and executes the
191/// operation with [`ValidatedOperation::execute()`].
192pub async fn execute<'a, S, QueryT, MutationT, SubscriptionT>(
193    document_source: &'a str,
194    operation_name: Option<&str>,
195    root_node: &'a RootNode<QueryT, MutationT, SubscriptionT, S>,
196    variables: &Variables<S>,
197    context: &QueryT::Context,
198) -> Result<(Value<S>, Vec<ExecutionError<S>>), GraphQLError>
199where
200    QueryT: GraphQLTypeAsync<S>,
201    QueryT::TypeInfo: Sync,
202    QueryT::Context: Sync,
203    MutationT: GraphQLTypeAsync<S, Context = QueryT::Context>,
204    MutationT::TypeInfo: Sync,
205    SubscriptionT: GraphQLType<S, Context = QueryT::Context> + Sync,
206    SubscriptionT::TypeInfo: Sync,
207    S: ScalarValue + Send + Sync,
208{
209    ValidatedOperation::new(document_source, operation_name, root_node)?
210        .execute(variables, context)
211        .await
212}
213
214/// Resolves a subscription into a [`ValuesStream`] in the provided schema.
215///
216/// Parses and validates the document with [`ValidatedOperation::new()`] and resolves the
217/// operation with [`ValidatedOperation::resolve_into_stream()`].
218pub async fn resolve_into_stream<'a, S, QueryT, MutationT, SubscriptionT>(
219    document_source: &'a str,
220    operation_name: Option<&str>,
221    root_node: &'a RootNode<QueryT, MutationT, SubscriptionT, S>,
222    variables: &Variables<S>,
223    context: &'a QueryT::Context,
224) -> Result<(Value<ValuesStream<'a, S>>, Vec<ExecutionError<S>>), GraphQLError>
225where
226    QueryT: GraphQLTypeAsync<S>,
227    QueryT::TypeInfo: Sync,
228    QueryT::Context: Sync,
229    MutationT: GraphQLTypeAsync<S, Context = QueryT::Context>,
230    MutationT::TypeInfo: Sync,
231    SubscriptionT: GraphQLSubscriptionType<S, Context = QueryT::Context>,
232    SubscriptionT::TypeInfo: Sync,
233    S: ScalarValue + Send + Sync,
234{
235    ValidatedOperation::new(document_source, operation_name, root_node)?
236        .resolve_into_stream(variables, context)
237        .await
238}
239
240/// Executes the [canonical introspection query][0] in the provided schema.
241///
242/// [0]: https://github.com/graphql/graphql-js/blob/v16.11.0/src/utilities/getIntrospectionQuery.ts#L75
243pub fn introspect<S, QueryT, MutationT, SubscriptionT>(
244    root_node: &RootNode<QueryT, MutationT, SubscriptionT, S>,
245    context: &QueryT::Context,
246    format: IntrospectionFormat,
247) -> Result<(Value<S>, Vec<ExecutionError<S>>), GraphQLError>
248where
249    S: ScalarValue,
250    QueryT: GraphQLType<S>,
251    MutationT: GraphQLType<S, Context = QueryT::Context>,
252    SubscriptionT: GraphQLType<S, Context = QueryT::Context>,
253{
254    execute_sync(
255        match format {
256            IntrospectionFormat::All => INTROSPECTION_QUERY,
257            IntrospectionFormat::WithoutDescriptions => INTROSPECTION_QUERY_WITHOUT_DESCRIPTIONS,
258        },
259        None,
260        root_node,
261        &Variables::new(),
262        context,
263    )
264}