gurafi/traits.rs
1//! The traits that connect Rust types to GraphQL types.
2//!
3//! Every trait in this module is implemented by a derive macro or by hand for the built-in
4//! types. Together they are what makes a `gurafi` schema type-driven: a field's GraphQL type is
5//! derived from its Rust return type and its GraphQL arguments are derived from its Rust `Args`
6//! type.
7
8use crate::registry::TypeRegistry;
9use gql::{GraphQLError, TypeRef, Value};
10
11/// A Rust type that may appear in an output position.
12///
13/// The mapping is:
14///
15/// | Rust type | GraphQL type |
16/// | --- | --- |
17/// | `String`, `&str`, `Cow<str>` | `String!` |
18/// | `bool` | `Boolean!` |
19/// | `i8`, `i16`, `i32`, `u8`, `u16` | `Int!` |
20/// | `f32`, `f64` | `Float!` |
21/// | [`crate::ID`] | `ID!` |
22/// | `Option<T>` | `T` with the outer non-null removed |
23/// | `Vec<T>` | `[T]!`, keeping `T`'s own nullability |
24/// | `Box<T>`, `Arc<T>` | `T` |
25/// | [`crate::Raw`] | `T`'s GraphQL type, with a prebuilt value |
26/// | a derived object, enum, scalar or union | its GraphQL name |
27///
28/// There is deliberately no mapping from `Result<T, E>`: a fallible field is declared with one
29/// of the `*_result` methods so the schema builder can tell the two cases apart.
30pub trait OutputType {
31 /// The GraphQL type of values produced by this Rust type.
32 fn output_type() -> TypeRef;
33
34 /// Whether the Rust type is an `Option`.
35 ///
36 /// This is what lets [`crate::FieldConfig::non_null`] reject an override that claims a field
37 /// is non-null while its resolver can still return `None`. It is hidden from the docs because
38 /// it is an implementation detail of the builder, not something a schema author writes.
39 #[doc(hidden)]
40 fn is_optional() -> bool {
41 false
42 }
43
44 /// Register every named type this type depends on with the schema being built.
45 #[doc(hidden)]
46 fn register_output(registry: &mut TypeRegistry) {
47 let _ = registry;
48 }
49}
50
51/// A Rust type that may appear in an input position.
52///
53/// The mapping mirrors [`OutputType`]. `Option<T>` makes a field optional in the GraphQL schema,
54/// and `Vec<T>` becomes a list.
55pub trait InputType {
56 /// The GraphQL input type for values of this Rust type.
57 fn input_type() -> TypeRef;
58
59 /// Register every named type this type depends on with the schema being built.
60 #[doc(hidden)]
61 fn register_input(registry: &mut TypeRegistry) {
62 let _ = registry;
63 }
64}
65
66/// Convert a Rust value into the executor's value model.
67///
68/// Most conversions cannot fail. Custom scalars can: their output form may need validation, and
69/// a failure is reported as a field error rather than silently serialised as `null`.
70pub trait IntoValue {
71 /// Convert `self` into a GraphQL value.
72 ///
73 /// # Errors
74 ///
75 /// Returns an error when a custom scalar cannot represent the value.
76 fn into_value(self) -> Result<Value, GraphQLError>;
77}
78
79/// Convert an input value into a Rust type.
80pub trait FromValue: Sized {
81 /// Convert a GraphQL value into `Self`.
82 ///
83 /// # Errors
84 ///
85 /// Returns an error when the value does not match the type. The executor turns this into a
86 /// normal per-field GraphQL error.
87 fn from_value(value: &Value) -> Result<Self, GraphQLError>;
88}
89
90/// A Rust struct that is a GraphQL object type.
91///
92/// Implemented by `#[derive(Object)]`. The resolver for each field is declared on the schema
93/// builder, not here, because fields need access to context, arguments and authorization.
94pub trait ObjectModel: Sized + Send + Sync + 'static {
95 /// The GraphQL type name.
96 const NAME: &'static str;
97
98 /// The type's description, if any.
99 fn description() -> Option<&'static str> {
100 None
101 }
102}
103
104/// A Rust enum that is a GraphQL enum.
105///
106/// Implemented by `#[derive(Enum)]`.
107pub trait EnumModel: Sized + Send + Sync + 'static {
108 /// The GraphQL type name.
109 const NAME: &'static str;
110
111 /// The type's description, if any.
112 fn description() -> Option<&'static str> {
113 None
114 }
115
116 /// Every value, in declaration order.
117 fn values() -> Vec<gql::EnumValue>;
118
119 /// The GraphQL name of this value.
120 fn value_name(&self) -> &'static str;
121
122 /// Look up a value by its GraphQL name.
123 fn from_name(name: &str) -> Option<Self>;
124}
125
126/// A Rust enum that is a GraphQL union.
127///
128/// Implemented by `#[derive(Union)]`. The union's members are still declared on the schema with
129/// [`crate::Schema::union`], where the rest of the schema is visible.
130pub trait UnionModel: Sized + Send + Sync + 'static {
131 /// The GraphQL type name.
132 const NAME: &'static str;
133
134 /// The type's description, if any.
135 fn description() -> Option<&'static str> {
136 None
137 }
138}
139
140/// A Rust newtype that is a custom GraphQL scalar.
141///
142/// Implement it by hand when the scalar's representation is not simply its inner type's; the
143/// `#[derive(Scalar)]` macro implements it for newtypes that delegate to their inner type. A
144/// manual implementation also needs the conversion impls; the [`crate::impl_scalar_traits`]
145/// macro writes them.
146pub trait ScalarValue: Sized + Send + Sync + 'static {
147 /// The GraphQL type name.
148 const NAME: &'static str;
149
150 /// The type's description, if any.
151 fn description() -> Option<&'static str> {
152 None
153 }
154
155 /// The `@specifiedBy` URL, if any.
156 fn specified_by() -> Option<&'static str> {
157 None
158 }
159
160 /// Serialize this value into its GraphQL representation.
161 ///
162 /// # Errors
163 ///
164 /// Returns an error when the value cannot be represented. It becomes a field error.
165 fn to_value(&self) -> Result<Value, GraphQLError>;
166
167 /// Parse an input value into `Self`.
168 ///
169 /// # Errors
170 ///
171 /// Returns an error when the value is not a valid scalar value.
172 fn from_value(value: &Value) -> Result<Self, GraphQLError>;
173
174 /// Coerce a GraphQL literal into the scalar's runtime representation.
175 ///
176 /// The default accepts the ordinary scalar literals. Override it for scalars whose literals
177 /// need a different representation.
178 ///
179 /// # Errors
180 ///
181 /// Returns an error when the literal is not valid for this scalar.
182 fn from_literal(literal: &gql::ast::Value<'_>) -> Result<Value, GraphQLError> {
183 crate::value::literal_to_value(literal)
184 }
185}
186
187/// A Rust struct that is a GraphQL input object, and can be used as a field's arguments.
188///
189/// Implemented by `#[derive(Input)]`. Use [`crate::NoArgs`] (which is `()`) for fields that
190/// take no arguments.
191pub trait InputObject: Sized + Send + 'static {
192 /// The GraphQL input object name, or `None` when the type only describes arguments.
193 ///
194 /// `#[derive(Input)]` deliberately produces `None` unless the type carries
195 /// `#[graphql(name = "...")]`. An args type is not a named input object: its fields become
196 /// the field's arguments, and no `FilterInput` type leaks into the schema on its own. Add a
197 /// name when the type is also used nested inside another input object (or by several
198 /// fields), so it becomes a reusable GraphQL input object.
199 const NAME: Option<&'static str>;
200
201 /// The type's description, if any.
202 fn description() -> Option<&'static str> {
203 None
204 }
205
206 /// Whether this input object is a `@oneOf` input.
207 ///
208 /// A one-of input has only nullable fields, no defaults, and requires callers to provide
209 /// exactly one non-null field. Set it with `#[graphql(one_of)]` (which also requires a
210 /// GraphQL name, because the type must exist in the schema to carry the directive).
211 fn one_of() -> bool {
212 false
213 }
214
215 /// Validate coerced input after every field has been read.
216 ///
217 /// Called by the schema builder after [`InputObject::from_object`] and before the resolver.
218 /// Implementations can check cross-field rules that individual field coercion cannot express.
219 /// The default accepts every value.
220 ///
221 /// # Errors
222 ///
223 /// Returns an error when the value is invalid. The error becomes a normal GraphQL field
224 /// error with the input type and field path attached.
225 fn validate(&self) -> Result<(), GraphQLError> {
226 Ok(())
227 }
228
229 /// The input fields, with descriptions, defaults and deprecations applied.
230 ///
231 /// # Errors
232 ///
233 /// Returns an error when a default value cannot be serialised.
234 fn fields() -> Result<Vec<gql::InputValue>, GraphQLError>;
235
236 /// Read the arguments from the executor's coerced argument object.
237 ///
238 /// # Errors
239 ///
240 /// Returns an error when a field is missing or has the wrong shape.
241 fn from_object(input: &gql::Object) -> Result<Self, GraphQLError>;
242
243 /// Register this type and the nested input types used by its fields.
244 ///
245 /// Used when the type appears as a field's arguments. [`crate::NoArgs`] registers nothing.
246 #[doc(hidden)]
247 fn register_args(registry: &mut TypeRegistry) {
248 let _ = registry;
249 }
250}
251
252impl InputObject for () {
253 const NAME: Option<&'static str> = None;
254
255 fn fields() -> Result<Vec<gql::InputValue>, GraphQLError> {
256 Ok(Vec::new())
257 }
258
259 fn from_object(_: &gql::Object) -> Result<Self, GraphQLError> {
260 Ok(())
261 }
262}
263
264/// The arguments type for a field that takes no arguments.
265pub type NoArgs = ();
266
267/// A GraphQL abstract type: an interface or a union.
268///
269/// Values of this type are cheap witnesses returned by the schema builder; they are used by
270/// [`crate::FieldConfig::as_abstract`] and by [`crate::ObjectBuilder::implements`]. The name is
271/// borrowed from the witness rather than `'static`, so it can be computed at runtime.
272pub trait AbstractType {
273 /// The GraphQL type name.
274 fn abstract_name(&self) -> &str;
275}
276
277impl<T: AbstractType + ?Sized> AbstractType for &T {
278 fn abstract_name(&self) -> &str {
279 (*self).abstract_name()
280 }
281}
282
283/// A safe downcast from the executor's parent value to an object model.
284pub(crate) fn model_ref<'a, M: ObjectModel>(
285 parent: &'a Value,
286 parent_type: &str,
287 field_name: &str,
288) -> Result<&'a M, GraphQLError> {
289 parent.as_external::<M>().ok_or_else(|| {
290 GraphQLError::new(format!(
291 "Internal error: field \"{parent_type}.{field_name}\" expected a `{}` parent.",
292 M::NAME
293 ))
294 })
295}
296
297/// Coerce the executor's argument object into a typed args value, adding field context to any
298/// error, and run the input type's own validation once.
299pub(crate) fn coerce_args<A: InputObject>(
300 args: &gql::Object,
301 parent_type: &str,
302 field_name: &str,
303) -> Result<A, GraphQLError> {
304 let value = coerce_args_without_validation::<A>(args, parent_type, field_name)?;
305 value.validate().map_err(|error| {
306 GraphQLError::new(format!(
307 "Invalid arguments for \"{parent_type}.{field_name}\": {}",
308 error.message()
309 ))
310 .extend("code", "BAD_USER_INPUT")
311 })?;
312 Ok(value)
313}
314
315/// Coerce arguments without running [`InputObject::validate`].
316///
317/// Subscription events use this after the setup path already validated the arguments, so a
318/// per-event validation hook does not turn input-level validation into a per-event side effect.
319pub(crate) fn coerce_args_without_validation<A: InputObject>(
320 args: &gql::Object,
321 parent_type: &str,
322 field_name: &str,
323) -> Result<A, GraphQLError> {
324 A::from_object(args).map_err(|error| {
325 GraphQLError::new(format!(
326 "Invalid arguments for \"{parent_type}.{field_name}\": {}",
327 error.message()
328 ))
329 .extend("code", "BAD_USER_INPUT")
330 })
331}