Struct async_graphql::Error

source ·
pub struct Error {
    pub message: String,
    pub source: Option<Arc<dyn Any + Send + Sync>>,
    pub extensions: Option<ErrorExtensionValues>,
}
Expand description

An error with a message and optional extensions.

Fields§

§message: String

The error message.

§source: Option<Arc<dyn Any + Send + Sync>>

The source of the error.

§extensions: Option<ErrorExtensionValues>

Extensions to the error.

Implementations§

Create an error from the given error message.

Examples found in repository?
src/dynamic/field.rs (line 188)
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
    pub fn try_to_value(&self) -> Result<&Value> {
        self.as_value()
            .ok_or_else(|| Error::new("internal: not a Value"))
    }

    /// If the FieldValue is a list, returns the associated
    /// vector. Returns `None` otherwise.
    #[inline]
    pub fn as_list(&self) -> Option<&[FieldValue]> {
        match &self.0 {
            FieldValueInner::List(values) => Some(values),
            _ => None,
        }
    }

    /// Like `as_list`, but returns `Result`.
    #[inline]
    pub fn try_to_list(&self) -> Result<&[FieldValue]> {
        self.as_list()
            .ok_or_else(|| Error::new("internal: not a list"))
    }

    /// If the FieldValue is a any, returns the associated
    /// vector. Returns `None` otherwise.
    #[inline]
    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
        match &self.0 {
            FieldValueInner::BorrowedAny(value) => value.downcast_ref::<T>(),
            FieldValueInner::OwnedAny(value) => value.downcast_ref::<T>(),
            _ => None,
        }
    }

    /// Like `downcast_ref`, but returns `Result`.
    #[inline]
    pub fn try_downcast_ref<T: Any>(&self) -> Result<&T> {
        self.downcast_ref().ok_or_else(|| {
            Error::new(format!(
                "internal: not type \"{}\"",
                std::any::type_name::<T>()
            ))
        })
    }
More examples
Hide additional examples
src/dynamic/value_accessor.rs (line 22)
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
    pub fn boolean(&self) -> Result<bool> {
        match self.0 {
            Value::Boolean(b) => Ok(*b),
            _ => Err(Error::new("internal: not a boolean")),
        }
    }

    /// Returns the enum name
    pub fn enum_name(&self) -> Result<&str> {
        match self.0 {
            Value::Enum(s) => Ok(s),
            Value::String(s) => Ok(s.as_str()),
            _ => Err(Error::new("internal: not an enum name")),
        }
    }

    /// Returns the number as `i64`
    pub fn i64(&self) -> Result<i64> {
        if let Value::Number(number) = self.0 {
            if let Some(value) = number.as_i64() {
                return Ok(value);
            }
        }
        Err(Error::new("internal: not an signed integer"))
    }

    /// Returns the number as `u64`
    pub fn u64(&self) -> Result<u64> {
        if let Value::Number(number) = self.0 {
            if let Some(value) = number.as_u64() {
                return Ok(value);
            }
        }
        Err(Error::new("internal: not an unsigned integer"))
    }

    /// Returns the number as `f32`
    pub fn f32(&self) -> Result<f32> {
        if let Value::Number(number) = self.0 {
            if let Some(value) = number.as_f64() {
                return Ok(value as f32);
            }
        }
        Err(Error::new("internal: not a float"))
    }

    /// Returns the number as `f64`
    pub fn f64(&self) -> Result<f64> {
        if let Value::Number(number) = self.0 {
            if let Some(value) = number.as_f64() {
                return Ok(value);
            }
        }
        Err(Error::new("internal: not a float"))
    }

    /// Returns the string value
    pub fn string(&self) -> Result<&str> {
        if let Value::String(value) = self.0 {
            Ok(value)
        } else {
            Err(Error::new("internal: not a string"))
        }
    }

    /// Returns the object accessor
    pub fn object(&self) -> Result<ObjectAccessor<'_>> {
        if let Value::Object(obj) = self.0 {
            Ok(ObjectAccessor(Cow::Borrowed(obj)))
        } else {
            Err(Error::new("internal: not a string"))
        }
    }

    /// Returns the list accessor
    pub fn list(&self) -> Result<ListAccessor<'_>> {
        if let Value::List(list) = self.0 {
            Ok(ListAccessor(list))
        } else {
            Err(Error::new("internal: not a list"))
        }
    }

    /// Deserialize the value to `T`
    pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T> {
        T::deserialize(self.0.clone()).map_err(|err| format!("internal: {}", err).into())
    }
}

/// A object accessor
pub struct ObjectAccessor<'a>(pub(crate) Cow<'a, IndexMap<Name, Value>>);

impl<'a> ObjectAccessor<'a> {
    /// Return a reference to the value stored for `key`, if it is present,
    /// else `None`.
    #[inline]
    pub fn get(&'a self, name: &str) -> Option<ValueAccessor<'a>> {
        self.0.get(name).map(ValueAccessor)
    }

    /// Like [`ObjectAccessor::get`], returns `Err` if the index does not exist
    #[inline]
    pub fn try_get(&'a self, name: &str) -> Result<ValueAccessor<'a>> {
        self.0
            .get(name)
            .map(ValueAccessor)
            .ok_or_else(|| Error::new(format!("internal: key \"{}\" not found", name)))
    }

    /// Return an iterator over the key-value pairs of the object, in their
    /// order
    #[inline]
    pub fn iter(&'a self) -> impl Iterator<Item = (&Name, ValueAccessor<'_>)> + 'a {
        self.0
            .iter()
            .map(|(name, value)| (name, ValueAccessor(value)))
    }
}

/// A list accessor
pub struct ListAccessor<'a>(pub(crate) &'a [Value]);

impl<'a> ListAccessor<'a> {
    /// Returns the number of elements in the list
    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` if the list has a length of 0
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns an iterator over the list
    #[inline]
    pub fn iter(&'a self) -> impl Iterator<Item = ValueAccessor<'_>> + 'a {
        self.0.iter().map(ValueAccessor)
    }

    /// Returns a reference to an element depending on the index
    #[inline]
    pub fn get(&self, idx: usize) -> Option<ValueAccessor<'a>> {
        self.0.get(idx).map(ValueAccessor)
    }

    /// Like [`ListAccessor::get`], returns `Err` if the index does not exist
    #[inline]
    pub fn try_get(&self, idx: usize) -> Result<ValueAccessor<'a>> {
        self.get(idx)
            .ok_or_else(|| Error::new(format!("internal: index \"{}\" not found", idx)))
    }
src/context.rs (lines 380-383)
378
379
380
381
382
383
384
385
    pub fn data<D: Any + Send + Sync>(&self) -> Result<&'a D> {
        self.data_opt::<D>().ok_or_else(|| {
            Error::new(format!(
                "Data `{}` does not exist.",
                std::any::type_name::<D>()
            ))
        })
    }
src/extensions/mod.rs (lines 84-87)
82
83
84
85
86
87
88
89
    pub fn data<D: Any + Send + Sync>(&self) -> Result<&'a D> {
        self.data_opt::<D>().ok_or_else(|| {
            Error::new(format!(
                "Data `{}` does not exist.",
                std::any::type_name::<D>()
            ))
        })
    }
src/http/websocket.rs (lines 206-208)
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        let mut this = self.project();

        if this.init_fut.is_none() {
            while let Poll::Ready(message) = Pin::new(&mut this.stream).poll_next(cx) {
                let message = match message {
                    Some(message) => message,
                    None => return Poll::Ready(None),
                };

                let message: ClientMessage = match message {
                    Ok(message) => message,
                    Err(err) => return Poll::Ready(Some(WsMessage::Close(1002, err.to_string()))),
                };

                match message {
                    ClientMessage::ConnectionInit { payload } => {
                        if let Some(on_connection_init) = this.on_connection_init.take() {
                            *this.init_fut = Some(Box::pin(async move {
                                on_connection_init(payload.unwrap_or_default()).await
                            }));
                            break;
                        } else {
                            match this.protocol {
                                Protocols::SubscriptionsTransportWS => {
                                    return Poll::Ready(Some(WsMessage::Text(
                                        serde_json::to_string(&ServerMessage::ConnectionError {
                                            payload: Error::new(
                                                "Too many initialisation requests.",
                                            ),
                                        })
                                        .unwrap(),
                                    )));
                                }
                                Protocols::GraphQLWS => {
                                    return Poll::Ready(Some(WsMessage::Close(
                                        4429,
                                        "Too many initialisation requests.".to_string(),
                                    )));
                                }
                            }
                        }
                    }
                    ClientMessage::Start {
                        id,
                        payload: request,
                    } => {
                        if let Some(data) = this.data.clone() {
                            this.streams.insert(
                                id,
                                Box::pin(this.executor.execute_stream(request, Some(data))),
                            );
                        } else {
                            return Poll::Ready(Some(WsMessage::Close(
                                1011,
                                "The handshake is not completed.".to_string(),
                            )));
                        }
                    }
                    ClientMessage::Stop { id } => {
                        if this.streams.remove(&id).is_some() {
                            return Poll::Ready(Some(WsMessage::Text(
                                serde_json::to_string(&ServerMessage::Complete { id: &id })
                                    .unwrap(),
                            )));
                        }
                    }
                    // Note: in the revised `graphql-ws` spec, there is no equivalent to the
                    // `CONNECTION_TERMINATE` `client -> server` message; rather, disconnection is
                    // handled by disconnecting the websocket
                    ClientMessage::ConnectionTerminate => return Poll::Ready(None),
                    // Pong must be sent in response from the receiving party as soon as possible.
                    ClientMessage::Ping { .. } => {
                        return Poll::Ready(Some(WsMessage::Text(
                            serde_json::to_string(&ServerMessage::Pong { payload: None }).unwrap(),
                        )));
                    }
                    ClientMessage::Pong { .. } => {
                        // Do nothing...
                    }
                }
            }
        }

        if let Some(init_fut) = this.init_fut {
            if let Poll::Ready(res) = init_fut.poll_unpin(cx) {
                *this.init_fut = None;
                return match res {
                    Ok(data) => {
                        let mut ctx_data = this.connection_data.take().unwrap_or_default();
                        ctx_data.merge(data);
                        *this.data = Some(Arc::new(ctx_data));
                        Poll::Ready(Some(WsMessage::Text(
                            serde_json::to_string(&ServerMessage::ConnectionAck).unwrap(),
                        )))
                    }
                    Err(err) => match this.protocol {
                        Protocols::SubscriptionsTransportWS => Poll::Ready(Some(WsMessage::Text(
                            serde_json::to_string(&ServerMessage::ConnectionError {
                                payload: Error::new(err.message),
                            })
                            .unwrap(),
                        ))),
                        Protocols::GraphQLWS => {
                            Poll::Ready(Some(WsMessage::Close(1002, err.message)))
                        }
                    },
                };
            }
        }

        for (id, stream) in &mut *this.streams {
            match Pin::new(stream).poll_next(cx) {
                Poll::Ready(Some(payload)) => {
                    return Poll::Ready(Some(WsMessage::Text(
                        serde_json::to_string(&this.protocol.next_message(id, payload)).unwrap(),
                    )));
                }
                Poll::Ready(None) => {
                    let id = id.clone();
                    this.streams.remove(&id);
                    return Poll::Ready(Some(WsMessage::Text(
                        serde_json::to_string(&ServerMessage::Complete { id: &id }).unwrap(),
                    )));
                }
                Poll::Pending => {}
            }
        }

        Poll::Pending
    }
}

/// Specification of which GraphQL Over WebSockets protocol is being utilized
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Protocols {
    /// [subscriptions-transport-ws protocol](https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md).
    SubscriptionsTransportWS,
    /// [graphql-ws protocol](https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md).
    GraphQLWS,
}

impl Protocols {
    /// Returns the `Sec-WebSocket-Protocol` header value for the protocol
    pub fn sec_websocket_protocol(&self) -> &'static str {
        match self {
            Protocols::SubscriptionsTransportWS => "graphql-ws",
            Protocols::GraphQLWS => "graphql-transport-ws",
        }
    }

    #[inline]
    fn next_message<'s>(&self, id: &'s str, payload: Response) -> ServerMessage<'s> {
        match self {
            Protocols::SubscriptionsTransportWS => ServerMessage::Data { id, payload },
            Protocols::GraphQLWS => ServerMessage::Next { id, payload },
        }
    }
}

impl std::str::FromStr for Protocols {
    type Err = Error;

    fn from_str(protocol: &str) -> Result<Self, Self::Err> {
        if protocol.eq_ignore_ascii_case("graphql-ws") {
            Ok(Protocols::SubscriptionsTransportWS)
        } else if protocol.eq_ignore_ascii_case("graphql-transport-ws") {
            Ok(Protocols::GraphQLWS)
        } else {
            Err(Error::new(format!(
                "Unsupported Sec-WebSocket-Protocol: {}",
                protocol
            )))
        }
    }
src/dynamic/resolve.rs (line 171)
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
fn collect_fields<'a>(
    fields: &mut Vec<BoxFieldFuture<'a>>,
    schema: &'a Schema,
    object: &'a Object,
    ctx: &ContextSelectionSet<'a>,
    parent_value: &'a FieldValue,
) -> ServerResult<()> {
    for selection in &ctx.item.node.items {
        match &selection.node {
            Selection::Field(field) => {
                if field.node.name.node == "__typename" {
                    if matches!(
                        ctx.schema_env.registry.introspection_mode,
                        IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly
                    ) && matches!(
                        ctx.query_env.introspection_mode,
                        IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly,
                    ) {
                        fields.push(
                            async move {
                                Ok((
                                    field.node.response_key().node.clone(),
                                    Value::from(object.name.as_str()),
                                ))
                            }
                            .boxed(),
                        )
                    } else {
                        fields.push(
                            async move { Ok((field.node.response_key().node.clone(), Value::Null)) }.boxed(),
                        )
                    }
                    continue;
                }

                if object.name == schema.0.env.registry.query_type
                    && matches!(
                        ctx.schema_env.registry.introspection_mode,
                        IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly
                    )
                    && matches!(
                        ctx.query_env.introspection_mode,
                        IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly,
                    )
                {
                    // is query root
                    if field.node.name.node == "__schema" {
                        let ctx = ctx.clone();
                        fields.push(
                            async move {
                                let ctx_field = ctx.with_field(field);
                                let mut ctx_obj =
                                    ctx.with_selection_set(&ctx_field.item.node.selection_set);
                                ctx_obj.is_for_introspection = true;
                                let visible_types =
                                    ctx.schema_env.registry.find_visible_types(&ctx_field);
                                let value = crate::OutputType::resolve(
                                    &crate::model::__Schema::new(
                                        &ctx.schema_env.registry,
                                        &visible_types,
                                    ),
                                    &ctx_obj,
                                    ctx_field.item,
                                )
                                .await?;
                                Ok((field.node.response_key().node.clone(), value))
                            }
                            .boxed(),
                        );
                        continue;
                    } else if field.node.name.node == "__type" {
                        let ctx = ctx.clone();
                        fields.push(
                            async move {
                                let ctx_field = ctx.with_field(field);
                                let (_, type_name) =
                                    ctx_field.param_value::<String>("name", None)?;
                                let mut ctx_obj =
                                    ctx.with_selection_set(&ctx_field.item.node.selection_set);
                                ctx_obj.is_for_introspection = true;
                                let visible_types =
                                    ctx.schema_env.registry.find_visible_types(&ctx_field);
                                let value = crate::OutputType::resolve(
                                    &ctx.schema_env
                                        .registry
                                        .types
                                        .get(&type_name)
                                        .filter(|_| visible_types.contains(type_name.as_str()))
                                        .map(|ty| {
                                            crate::model::__Type::new_simple(
                                                &ctx.schema_env.registry,
                                                &visible_types,
                                                ty,
                                            )
                                        }),
                                    &ctx_obj,
                                    ctx_field.item,
                                )
                                .await?;
                                Ok((field.node.response_key().node.clone(), value))
                            }
                            .boxed(),
                        );
                        continue;
                    } else if ctx.schema_env.registry.enable_federation
                        && field.node.name.node == "_service"
                    {
                        let sdl = ctx
                            .schema_env
                            .registry
                            .export_sdl(SDLExportOptions::new().federation());
                        fields.push(
                            async move {
                                Ok((field.node.response_key().node.clone(), Value::from(sdl)))
                            }
                            .boxed(),
                        );
                        continue;
                    } else if ctx.schema_env.registry.enable_federation
                        && field.node.name.node == "_entities"
                    {
                        let ctx = ctx.clone();
                        fields.push(
                            async move {
                                let ctx_field = ctx.with_field(field);
                                let entity_resolver =
                                    schema.0.entity_resolver.as_ref().ok_or_else(|| {
                                        ctx_field.set_error_path(
                                            Error::new("internal: missing entity resolver")
                                                .into_server_error(ctx_field.item.pos),
                                        )
                                    })?;
                                let entity_type = TypeRef::named_list_nn("_Entity");

                                let arguments = ObjectAccessor(Cow::Owned(
                                    field
                                        .node
                                        .arguments
                                        .iter()
                                        .map(|(name, value)| {
                                            ctx_field
                                                .resolve_input_value(value.clone())
                                                .map(|value| (name.node.clone(), value))
                                        })
                                        .collect::<ServerResult<IndexMap<Name, Value>>>()?,
                                ));

                                let field_value = (entity_resolver)(ResolverContext {
                                    ctx: &ctx_field,
                                    args: arguments,
                                    parent_value,
                                })
                                .0
                                .await
                                .map_err(|err| err.into_server_error(field.pos))?;
                                let value = resolve(
                                    schema,
                                    &ctx_field,
                                    &entity_type.0,
                                    field_value.as_ref(),
                                )
                                .await?
                                .unwrap_or_default();
                                Ok((field.node.response_key().node.clone(), value))
                            }
                            .boxed(),
                        );
                        continue;
                    }
                }

                if ctx.schema_env.registry.introspection_mode
                    == IntrospectionMode::IntrospectionOnly
                    || ctx.query_env.introspection_mode == IntrospectionMode::IntrospectionOnly
                {
                    fields.push(
                        async move { Ok((field.node.response_key().node.clone(), Value::Null)) }
                            .boxed(),
                    );
                    continue;
                }

                if let Some(field_def) = object.fields.get(field.node.name.node.as_str()) {
                    let ctx = ctx.clone();
                    fields.push(
                        async move {
                            let ctx_field = ctx.with_field(field);
                            let arguments = ObjectAccessor(Cow::Owned(
                                field
                                    .node
                                    .arguments
                                    .iter()
                                    .map(|(name, value)| {
                                        ctx_field
                                            .resolve_input_value(value.clone())
                                            .map(|value| (name.node.clone(), value))
                                    })
                                    .collect::<ServerResult<IndexMap<Name, Value>>>()?,
                            ));

                            let resolve_info = ResolveInfo {
                                path_node: ctx_field.path_node.as_ref().unwrap(),
                                parent_type: &object.name,
                                return_type: &field_def.ty.to_string(),
                                name: &field.node.name.node,
                                alias: field.node.alias.as_ref().map(|alias| &*alias.node),
                                is_for_introspection: ctx_field.is_for_introspection,
                            };

                            let resolve_fut = async {
                                let field_value = (field_def.resolver_fn)(ResolverContext {
                                    ctx: &ctx_field,
                                    args: arguments,
                                    parent_value,
                                })
                                .0
                                .await
                                .map_err(|err| err.into_server_error(field.pos))?;
                                let value = resolve(
                                    schema,
                                    &ctx_field,
                                    &field_def.ty.0,
                                    field_value.as_ref(),
                                )
                                .await?;
                                Ok(value)
                            };
                            futures_util::pin_mut!(resolve_fut);

                            let res_value = ctx_field
                                .query_env
                                .extensions
                                .resolve(resolve_info, &mut resolve_fut)
                                .await?
                                .unwrap_or_default();
                            Ok((field.node.response_key().node.clone(), res_value))
                        }
                        .boxed(),
                    );
                }
            }
            selection => {
                let (type_condition, selection_set) = match selection {
                    Selection::Field(_) => unreachable!(),
                    Selection::FragmentSpread(spread) => {
                        let fragment = ctx.query_env.fragments.get(&spread.node.fragment_name.node);
                        let fragment = match fragment {
                            Some(fragment) => fragment,
                            None => {
                                return Err(ServerError::new(
                                    format!(
                                        "Unknown fragment \"{}\".",
                                        spread.node.fragment_name.node
                                    ),
                                    Some(spread.pos),
                                ));
                            }
                        };
                        (
                            Some(&fragment.node.type_condition),
                            &fragment.node.selection_set,
                        )
                    }
                    Selection::InlineFragment(fragment) => (
                        fragment.node.type_condition.as_ref(),
                        &fragment.node.selection_set,
                    ),
                };

                let type_condition =
                    type_condition.map(|condition| condition.node.on.node.as_str());
                let introspection_type_name = &object.name;

                if type_condition.is_none() || type_condition == Some(introspection_type_name) {
                    collect_fields(
                        fields,
                        schema,
                        object,
                        &ctx.with_selection_set(selection_set),
                        parent_value,
                    )?;
                }
            }
        }
    }

    Ok(())
}

pub(crate) fn resolve<'a>(
    schema: &'a Schema,
    ctx: &'a Context<'a>,
    type_ref: &'a TypeRefInner,
    value: Option<&'a FieldValue>,
) -> BoxFuture<'a, ServerResult<Option<Value>>> {
    async move {
        match (type_ref, value) {
            (TypeRefInner::Named(type_name), Some(value)) => {
                resolve_value(schema, ctx, &schema.0.types[type_name.as_ref()], value).await
            }
            (TypeRefInner::Named(_), None) => Ok(None),

            (TypeRefInner::NonNull(type_ref), Some(value)) => {
                resolve(schema, ctx, type_ref, Some(value)).await
            }
            (TypeRefInner::NonNull(_), None) => Err(ctx.set_error_path(
                Error::new("internal: non-null types require a return value")
                    .into_server_error(ctx.item.pos),
            )),

            (TypeRefInner::List(type_ref), Some(FieldValue(FieldValueInner::List(values)))) => {
                resolve_list(schema, ctx, type_ref, values).await
            }
            (
                TypeRefInner::List(type_ref),
                Some(FieldValue(FieldValueInner::Value(Value::List(values)))),
            ) => {
                let values = values
                    .iter()
                    .cloned()
                    .map(FieldValue::value)
                    .collect::<Vec<_>>();
                resolve_list(schema, ctx, type_ref, &values).await
            }
            (TypeRefInner::List(_), Some(_)) => Err(ctx.set_error_path(
                Error::new("internal: expects an array").into_server_error(ctx.item.pos),
            )),
            (TypeRefInner::List(_), None) => Ok(Some(Value::List(vec![]))),
        }
    }
    .boxed()
}

async fn resolve_list<'a>(
    schema: &'a Schema,
    ctx: &'a Context<'a>,
    type_ref: &'a TypeRefInner,
    values: &[FieldValue<'_>],
) -> ServerResult<Option<Value>> {
    let mut futures = Vec::with_capacity(values.len());
    for (idx, value) in values.iter().enumerate() {
        let ctx_item = ctx.with_index(idx);

        futures.push(async move {
            let parent_type = format!("[{}]", type_ref);
            let return_type = type_ref.to_string();
            let resolve_info = ResolveInfo {
                path_node: ctx_item.path_node.as_ref().unwrap(),
                parent_type: &parent_type,
                return_type: &return_type,
                name: ctx.item.node.name.node.as_str(),
                alias: ctx
                    .item
                    .node
                    .alias
                    .as_ref()
                    .map(|alias| alias.node.as_str()),
                is_for_introspection: ctx_item.is_for_introspection,
            };

            let resolve_fut = async { resolve(schema, &ctx_item, type_ref, Some(value)).await };
            futures_util::pin_mut!(resolve_fut);

            let res_value = ctx_item
                .query_env
                .extensions
                .resolve(resolve_info, &mut resolve_fut)
                .await?;
            Ok::<_, ServerError>(res_value.unwrap_or_default())
        });
    }
    let values = futures_util::future::try_join_all(futures).await?;
    Ok(Some(Value::List(values)))
}

async fn resolve_value(
    schema: &Schema,
    ctx: &Context<'_>,
    field_type: &Type,
    value: &FieldValue<'_>,
) -> ServerResult<Option<Value>> {
    match (field_type, &value.0) {
        (Type::Scalar(scalar), FieldValueInner::Value(value)) if scalar.validate(value) => {
            Ok(Some(value.clone()))
        }
        (Type::Scalar(scalar), _) => Err(ctx.set_error_path(
            Error::new(format!(
                "internal: invalid value for scalar \"{}\", expected \"FieldValue::Value\"",
                scalar.name
            ))
            .into_server_error(ctx.item.pos),
        )),

        (Type::Object(object), _) => {
            resolve_container(
                schema,
                object,
                &ctx.with_selection_set(&ctx.item.node.selection_set),
                value,
                true,
            )
            .await
        }

        (Type::InputObject(obj), _) => Err(ctx.set_error_path(
            Error::new(format!(
                "internal: cannot use input object \"{}\" as output value",
                obj.name
            ))
            .into_server_error(ctx.item.pos),
        )),

        (Type::Enum(e), FieldValueInner::Value(Value::Enum(name))) => {
            if !e.enum_values.contains_key(name.as_str()) {
                return Err(ctx.set_error_path(
                    Error::new(format!("internal: invalid item for enum \"{}\"", e.name))
                        .into_server_error(ctx.item.pos),
                ));
            }
            Ok(Some(Value::Enum(name.clone())))
        }
        (Type::Enum(e), FieldValueInner::Value(Value::String(name))) => {
            if !e.enum_values.contains_key(name) {
                return Err(ctx.set_error_path(
                    Error::new(format!("internal: invalid item for enum \"{}\"", e.name))
                        .into_server_error(ctx.item.pos),
                ));
            }
            Ok(Some(Value::Enum(Name::new(name))))
        }
        (Type::Enum(e), _) => Err(ctx.set_error_path(
            Error::new(format!("internal: invalid item for enum \"{}\"", e.name))
                .into_server_error(ctx.item.pos),
        )),

        (Type::Interface(interface), FieldValueInner::WithType { value, ty }) => {
            let is_contains_obj = schema
                .0
                .env
                .registry
                .types
                .get(&interface.name)
                .and_then(|meta_type| {
                    meta_type
                        .possible_types()
                        .map(|possible_types| possible_types.contains(ty.as_ref()))
                })
                .unwrap_or_default();
            if !is_contains_obj {
                return Err(ctx.set_error_path(
                    Error::new(format!(
                        "internal: object \"{}\" does not implement interface \"{}\"",
                        ty, interface.name,
                    ))
                    .into_server_error(ctx.item.pos),
                ));
            }

            let object_type = schema
                .0
                .types
                .get(ty.as_ref())
                .ok_or_else(|| {
                    ctx.set_error_path(
                        Error::new(format!("internal: object \"{}\" does not registered", ty))
                            .into_server_error(ctx.item.pos),
                    )
                })?
                .as_object()
                .ok_or_else(|| {
                    ctx.set_error_path(
                        Error::new(format!("internal: type \"{}\" is not object", ty))
                            .into_server_error(ctx.item.pos),
                    )
                })?;

            resolve_container(
                schema,
                object_type,
                &ctx.with_selection_set(&ctx.item.node.selection_set),
                value,
                true,
            )
            .await
        }
        (Type::Interface(interface), _) => Err(ctx.set_error_path(
            Error::new(format!(
                "internal: invalid value for interface \"{}\", expected \"FieldValue::WithType\"",
                interface.name
            ))
            .into_server_error(ctx.item.pos),
        )),

        (Type::Union(union), FieldValueInner::WithType { value, ty }) => {
            if !union.possible_types.contains(ty.as_ref()) {
                return Err(ctx.set_error_path(
                    Error::new(format!(
                        "internal: union \"{}\" does not contain object \"{}\"",
                        union.name, ty,
                    ))
                    .into_server_error(ctx.item.pos),
                ));
            }

            let object_type = schema
                .0
                .types
                .get(ty.as_ref())
                .ok_or_else(|| {
                    ctx.set_error_path(
                        Error::new(format!("internal: object \"{}\" does not registered", ty))
                            .into_server_error(ctx.item.pos),
                    )
                })?
                .as_object()
                .ok_or_else(|| {
                    ctx.set_error_path(
                        Error::new(format!("internal: type \"{}\" is not object", ty))
                            .into_server_error(ctx.item.pos),
                    )
                })?;

            resolve_container(
                schema,
                object_type,
                &ctx.with_selection_set(&ctx.item.node.selection_set),
                value,
                true,
            )
            .await
        }
        (Type::Union(union), _) => Err(ctx.set_error_path(
            Error::new(format!(
                "internal: invalid value for union \"{}\", expected \"FieldValue::WithType\"",
                union.name
            ))
            .into_server_error(ctx.item.pos),
        )),

        (Type::Subscription(subscription), _) => Err(ctx.set_error_path(
            Error::new(format!(
                "internal: cannot use subscription \"{}\" as output value",
                subscription.name
            ))
            .into_server_error(ctx.item.pos),
        )),
    }
}

Create an error with a type that implements Display, and it will also set the source of the error to this value.

Convert the error to a server error.

Examples found in repository?
src/resolver_utils/container.rs (line 91)
88
89
90
91
92
93
94
95
96
97
98
99
100
    async fn resolve_field(&self, ctx: &Context<'_>) -> ServerResult<Option<Value>> {
        match self {
            Ok(value) => T::resolve_field(value, ctx).await,
            Err(err) => Err(ctx.set_error_path(err.clone().into().into_server_error(ctx.item.pos))),
        }
    }

    async fn find_entity(&self, ctx: &Context<'_>, params: &Value) -> ServerResult<Option<Value>> {
        match self {
            Ok(value) => T::find_entity(value, ctx, params).await,
            Err(err) => Err(ctx.set_error_path(err.clone().into().into_server_error(ctx.item.pos))),
        }
    }
More examples
Hide additional examples
src/base.rs (line 130)
122
123
124
125
126
127
128
129
130
131
132
133
    async fn resolve(
        &self,
        ctx: &ContextSelectionSet<'_>,
        field: &Positioned<Field>,
    ) -> ServerResult<Value> {
        match self {
            Ok(value) => value.resolve(ctx, field).await,
            Err(err) => {
                return Err(ctx.set_error_path(err.clone().into().into_server_error(field.pos)))
            }
        }
    }
src/dynamic/resolve.rs (line 172)
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
fn collect_fields<'a>(
    fields: &mut Vec<BoxFieldFuture<'a>>,
    schema: &'a Schema,
    object: &'a Object,
    ctx: &ContextSelectionSet<'a>,
    parent_value: &'a FieldValue,
) -> ServerResult<()> {
    for selection in &ctx.item.node.items {
        match &selection.node {
            Selection::Field(field) => {
                if field.node.name.node == "__typename" {
                    if matches!(
                        ctx.schema_env.registry.introspection_mode,
                        IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly
                    ) && matches!(
                        ctx.query_env.introspection_mode,
                        IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly,
                    ) {
                        fields.push(
                            async move {
                                Ok((
                                    field.node.response_key().node.clone(),
                                    Value::from(object.name.as_str()),
                                ))
                            }
                            .boxed(),
                        )
                    } else {
                        fields.push(
                            async move { Ok((field.node.response_key().node.clone(), Value::Null)) }.boxed(),
                        )
                    }
                    continue;
                }

                if object.name == schema.0.env.registry.query_type
                    && matches!(
                        ctx.schema_env.registry.introspection_mode,
                        IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly
                    )
                    && matches!(
                        ctx.query_env.introspection_mode,
                        IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly,
                    )
                {
                    // is query root
                    if field.node.name.node == "__schema" {
                        let ctx = ctx.clone();
                        fields.push(
                            async move {
                                let ctx_field = ctx.with_field(field);
                                let mut ctx_obj =
                                    ctx.with_selection_set(&ctx_field.item.node.selection_set);
                                ctx_obj.is_for_introspection = true;
                                let visible_types =
                                    ctx.schema_env.registry.find_visible_types(&ctx_field);
                                let value = crate::OutputType::resolve(
                                    &crate::model::__Schema::new(
                                        &ctx.schema_env.registry,
                                        &visible_types,
                                    ),
                                    &ctx_obj,
                                    ctx_field.item,
                                )
                                .await?;
                                Ok((field.node.response_key().node.clone(), value))
                            }
                            .boxed(),
                        );
                        continue;
                    } else if field.node.name.node == "__type" {
                        let ctx = ctx.clone();
                        fields.push(
                            async move {
                                let ctx_field = ctx.with_field(field);
                                let (_, type_name) =
                                    ctx_field.param_value::<String>("name", None)?;
                                let mut ctx_obj =
                                    ctx.with_selection_set(&ctx_field.item.node.selection_set);
                                ctx_obj.is_for_introspection = true;
                                let visible_types =
                                    ctx.schema_env.registry.find_visible_types(&ctx_field);
                                let value = crate::OutputType::resolve(
                                    &ctx.schema_env
                                        .registry
                                        .types
                                        .get(&type_name)
                                        .filter(|_| visible_types.contains(type_name.as_str()))
                                        .map(|ty| {
                                            crate::model::__Type::new_simple(
                                                &ctx.schema_env.registry,
                                                &visible_types,
                                                ty,
                                            )
                                        }),
                                    &ctx_obj,
                                    ctx_field.item,
                                )
                                .await?;
                                Ok((field.node.response_key().node.clone(), value))
                            }
                            .boxed(),
                        );
                        continue;
                    } else if ctx.schema_env.registry.enable_federation
                        && field.node.name.node == "_service"
                    {
                        let sdl = ctx
                            .schema_env
                            .registry
                            .export_sdl(SDLExportOptions::new().federation());
                        fields.push(
                            async move {
                                Ok((field.node.response_key().node.clone(), Value::from(sdl)))
                            }
                            .boxed(),
                        );
                        continue;
                    } else if ctx.schema_env.registry.enable_federation
                        && field.node.name.node == "_entities"
                    {
                        let ctx = ctx.clone();
                        fields.push(
                            async move {
                                let ctx_field = ctx.with_field(field);
                                let entity_resolver =
                                    schema.0.entity_resolver.as_ref().ok_or_else(|| {
                                        ctx_field.set_error_path(
                                            Error::new("internal: missing entity resolver")
                                                .into_server_error(ctx_field.item.pos),
                                        )
                                    })?;
                                let entity_type = TypeRef::named_list_nn("_Entity");

                                let arguments = ObjectAccessor(Cow::Owned(
                                    field
                                        .node
                                        .arguments
                                        .iter()
                                        .map(|(name, value)| {
                                            ctx_field
                                                .resolve_input_value(value.clone())
                                                .map(|value| (name.node.clone(), value))
                                        })
                                        .collect::<ServerResult<IndexMap<Name, Value>>>()?,
                                ));

                                let field_value = (entity_resolver)(ResolverContext {
                                    ctx: &ctx_field,
                                    args: arguments,
                                    parent_value,
                                })
                                .0
                                .await
                                .map_err(|err| err.into_server_error(field.pos))?;
                                let value = resolve(
                                    schema,
                                    &ctx_field,
                                    &entity_type.0,
                                    field_value.as_ref(),
                                )
                                .await?
                                .unwrap_or_default();
                                Ok((field.node.response_key().node.clone(), value))
                            }
                            .boxed(),
                        );
                        continue;
                    }
                }

                if ctx.schema_env.registry.introspection_mode
                    == IntrospectionMode::IntrospectionOnly
                    || ctx.query_env.introspection_mode == IntrospectionMode::IntrospectionOnly
                {
                    fields.push(
                        async move { Ok((field.node.response_key().node.clone(), Value::Null)) }
                            .boxed(),
                    );
                    continue;
                }

                if let Some(field_def) = object.fields.get(field.node.name.node.as_str()) {
                    let ctx = ctx.clone();
                    fields.push(
                        async move {
                            let ctx_field = ctx.with_field(field);
                            let arguments = ObjectAccessor(Cow::Owned(
                                field
                                    .node
                                    .arguments
                                    .iter()
                                    .map(|(name, value)| {
                                        ctx_field
                                            .resolve_input_value(value.clone())
                                            .map(|value| (name.node.clone(), value))
                                    })
                                    .collect::<ServerResult<IndexMap<Name, Value>>>()?,
                            ));

                            let resolve_info = ResolveInfo {
                                path_node: ctx_field.path_node.as_ref().unwrap(),
                                parent_type: &object.name,
                                return_type: &field_def.ty.to_string(),
                                name: &field.node.name.node,
                                alias: field.node.alias.as_ref().map(|alias| &*alias.node),
                                is_for_introspection: ctx_field.is_for_introspection,
                            };

                            let resolve_fut = async {
                                let field_value = (field_def.resolver_fn)(ResolverContext {
                                    ctx: &ctx_field,
                                    args: arguments,
                                    parent_value,
                                })
                                .0
                                .await
                                .map_err(|err| err.into_server_error(field.pos))?;
                                let value = resolve(
                                    schema,
                                    &ctx_field,
                                    &field_def.ty.0,
                                    field_value.as_ref(),
                                )
                                .await?;
                                Ok(value)
                            };
                            futures_util::pin_mut!(resolve_fut);

                            let res_value = ctx_field
                                .query_env
                                .extensions
                                .resolve(resolve_info, &mut resolve_fut)
                                .await?
                                .unwrap_or_default();
                            Ok((field.node.response_key().node.clone(), res_value))
                        }
                        .boxed(),
                    );
                }
            }
            selection => {
                let (type_condition, selection_set) = match selection {
                    Selection::Field(_) => unreachable!(),
                    Selection::FragmentSpread(spread) => {
                        let fragment = ctx.query_env.fragments.get(&spread.node.fragment_name.node);
                        let fragment = match fragment {
                            Some(fragment) => fragment,
                            None => {
                                return Err(ServerError::new(
                                    format!(
                                        "Unknown fragment \"{}\".",
                                        spread.node.fragment_name.node
                                    ),
                                    Some(spread.pos),
                                ));
                            }
                        };
                        (
                            Some(&fragment.node.type_condition),
                            &fragment.node.selection_set,
                        )
                    }
                    Selection::InlineFragment(fragment) => (
                        fragment.node.type_condition.as_ref(),
                        &fragment.node.selection_set,
                    ),
                };

                let type_condition =
                    type_condition.map(|condition| condition.node.on.node.as_str());
                let introspection_type_name = &object.name;

                if type_condition.is_none() || type_condition == Some(introspection_type_name) {
                    collect_fields(
                        fields,
                        schema,
                        object,
                        &ctx.with_selection_set(selection_set),
                        parent_value,
                    )?;
                }
            }
        }
    }

    Ok(())
}

pub(crate) fn resolve<'a>(
    schema: &'a Schema,
    ctx: &'a Context<'a>,
    type_ref: &'a TypeRefInner,
    value: Option<&'a FieldValue>,
) -> BoxFuture<'a, ServerResult<Option<Value>>> {
    async move {
        match (type_ref, value) {
            (TypeRefInner::Named(type_name), Some(value)) => {
                resolve_value(schema, ctx, &schema.0.types[type_name.as_ref()], value).await
            }
            (TypeRefInner::Named(_), None) => Ok(None),

            (TypeRefInner::NonNull(type_ref), Some(value)) => {
                resolve(schema, ctx, type_ref, Some(value)).await
            }
            (TypeRefInner::NonNull(_), None) => Err(ctx.set_error_path(
                Error::new("internal: non-null types require a return value")
                    .into_server_error(ctx.item.pos),
            )),

            (TypeRefInner::List(type_ref), Some(FieldValue(FieldValueInner::List(values)))) => {
                resolve_list(schema, ctx, type_ref, values).await
            }
            (
                TypeRefInner::List(type_ref),
                Some(FieldValue(FieldValueInner::Value(Value::List(values)))),
            ) => {
                let values = values
                    .iter()
                    .cloned()
                    .map(FieldValue::value)
                    .collect::<Vec<_>>();
                resolve_list(schema, ctx, type_ref, &values).await
            }
            (TypeRefInner::List(_), Some(_)) => Err(ctx.set_error_path(
                Error::new("internal: expects an array").into_server_error(ctx.item.pos),
            )),
            (TypeRefInner::List(_), None) => Ok(Some(Value::List(vec![]))),
        }
    }
    .boxed()
}

async fn resolve_list<'a>(
    schema: &'a Schema,
    ctx: &'a Context<'a>,
    type_ref: &'a TypeRefInner,
    values: &[FieldValue<'_>],
) -> ServerResult<Option<Value>> {
    let mut futures = Vec::with_capacity(values.len());
    for (idx, value) in values.iter().enumerate() {
        let ctx_item = ctx.with_index(idx);

        futures.push(async move {
            let parent_type = format!("[{}]", type_ref);
            let return_type = type_ref.to_string();
            let resolve_info = ResolveInfo {
                path_node: ctx_item.path_node.as_ref().unwrap(),
                parent_type: &parent_type,
                return_type: &return_type,
                name: ctx.item.node.name.node.as_str(),
                alias: ctx
                    .item
                    .node
                    .alias
                    .as_ref()
                    .map(|alias| alias.node.as_str()),
                is_for_introspection: ctx_item.is_for_introspection,
            };

            let resolve_fut = async { resolve(schema, &ctx_item, type_ref, Some(value)).await };
            futures_util::pin_mut!(resolve_fut);

            let res_value = ctx_item
                .query_env
                .extensions
                .resolve(resolve_info, &mut resolve_fut)
                .await?;
            Ok::<_, ServerError>(res_value.unwrap_or_default())
        });
    }
    let values = futures_util::future::try_join_all(futures).await?;
    Ok(Some(Value::List(values)))
}

async fn resolve_value(
    schema: &Schema,
    ctx: &Context<'_>,
    field_type: &Type,
    value: &FieldValue<'_>,
) -> ServerResult<Option<Value>> {
    match (field_type, &value.0) {
        (Type::Scalar(scalar), FieldValueInner::Value(value)) if scalar.validate(value) => {
            Ok(Some(value.clone()))
        }
        (Type::Scalar(scalar), _) => Err(ctx.set_error_path(
            Error::new(format!(
                "internal: invalid value for scalar \"{}\", expected \"FieldValue::Value\"",
                scalar.name
            ))
            .into_server_error(ctx.item.pos),
        )),

        (Type::Object(object), _) => {
            resolve_container(
                schema,
                object,
                &ctx.with_selection_set(&ctx.item.node.selection_set),
                value,
                true,
            )
            .await
        }

        (Type::InputObject(obj), _) => Err(ctx.set_error_path(
            Error::new(format!(
                "internal: cannot use input object \"{}\" as output value",
                obj.name
            ))
            .into_server_error(ctx.item.pos),
        )),

        (Type::Enum(e), FieldValueInner::Value(Value::Enum(name))) => {
            if !e.enum_values.contains_key(name.as_str()) {
                return Err(ctx.set_error_path(
                    Error::new(format!("internal: invalid item for enum \"{}\"", e.name))
                        .into_server_error(ctx.item.pos),
                ));
            }
            Ok(Some(Value::Enum(name.clone())))
        }
        (Type::Enum(e), FieldValueInner::Value(Value::String(name))) => {
            if !e.enum_values.contains_key(name) {
                return Err(ctx.set_error_path(
                    Error::new(format!("internal: invalid item for enum \"{}\"", e.name))
                        .into_server_error(ctx.item.pos),
                ));
            }
            Ok(Some(Value::Enum(Name::new(name))))
        }
        (Type::Enum(e), _) => Err(ctx.set_error_path(
            Error::new(format!("internal: invalid item for enum \"{}\"", e.name))
                .into_server_error(ctx.item.pos),
        )),

        (Type::Interface(interface), FieldValueInner::WithType { value, ty }) => {
            let is_contains_obj = schema
                .0
                .env
                .registry
                .types
                .get(&interface.name)
                .and_then(|meta_type| {
                    meta_type
                        .possible_types()
                        .map(|possible_types| possible_types.contains(ty.as_ref()))
                })
                .unwrap_or_default();
            if !is_contains_obj {
                return Err(ctx.set_error_path(
                    Error::new(format!(
                        "internal: object \"{}\" does not implement interface \"{}\"",
                        ty, interface.name,
                    ))
                    .into_server_error(ctx.item.pos),
                ));
            }

            let object_type = schema
                .0
                .types
                .get(ty.as_ref())
                .ok_or_else(|| {
                    ctx.set_error_path(
                        Error::new(format!("internal: object \"{}\" does not registered", ty))
                            .into_server_error(ctx.item.pos),
                    )
                })?
                .as_object()
                .ok_or_else(|| {
                    ctx.set_error_path(
                        Error::new(format!("internal: type \"{}\" is not object", ty))
                            .into_server_error(ctx.item.pos),
                    )
                })?;

            resolve_container(
                schema,
                object_type,
                &ctx.with_selection_set(&ctx.item.node.selection_set),
                value,
                true,
            )
            .await
        }
        (Type::Interface(interface), _) => Err(ctx.set_error_path(
            Error::new(format!(
                "internal: invalid value for interface \"{}\", expected \"FieldValue::WithType\"",
                interface.name
            ))
            .into_server_error(ctx.item.pos),
        )),

        (Type::Union(union), FieldValueInner::WithType { value, ty }) => {
            if !union.possible_types.contains(ty.as_ref()) {
                return Err(ctx.set_error_path(
                    Error::new(format!(
                        "internal: union \"{}\" does not contain object \"{}\"",
                        union.name, ty,
                    ))
                    .into_server_error(ctx.item.pos),
                ));
            }

            let object_type = schema
                .0
                .types
                .get(ty.as_ref())
                .ok_or_else(|| {
                    ctx.set_error_path(
                        Error::new(format!("internal: object \"{}\" does not registered", ty))
                            .into_server_error(ctx.item.pos),
                    )
                })?
                .as_object()
                .ok_or_else(|| {
                    ctx.set_error_path(
                        Error::new(format!("internal: type \"{}\" is not object", ty))
                            .into_server_error(ctx.item.pos),
                    )
                })?;

            resolve_container(
                schema,
                object_type,
                &ctx.with_selection_set(&ctx.item.node.selection_set),
                value,
                true,
            )
            .await
        }
        (Type::Union(union), _) => Err(ctx.set_error_path(
            Error::new(format!(
                "internal: invalid value for union \"{}\", expected \"FieldValue::WithType\"",
                union.name
            ))
            .into_server_error(ctx.item.pos),
        )),

        (Type::Subscription(subscription), _) => Err(ctx.set_error_path(
            Error::new(format!(
                "internal: cannot use subscription \"{}\" as output value",
                subscription.name
            ))
            .into_server_error(ctx.item.pos),
        )),
    }
}

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Convert the error to a Error.
Add extensions to the error, using a callback to make the extensions.
Converts to this type from the input type.
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Converts to this type from the input type.

Returns the argument unchanged.

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Attaches the current Context to this type, returning a WithContext wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more