Skip to main content

async_graphql_test/matchers/
should_be_not_null.rs

1use async_graphql::async_trait::async_trait;
2use async_graphql::{Context, CustomDirective, Directive, Error, ResolveFut, ServerResult, Value};
3
4use super::MatcherError;
5
6/// Use `@shouldBeNotNull` when you want to check that something is **not** null.
7#[Directive(location = "Field", name = "shouldBeNotNull")]
8pub fn should_be_not_null() -> impl CustomDirective {
9    ShouldBeNotNull
10}
11
12struct ShouldBeNotNull;
13
14#[async_trait]
15impl CustomDirective for ShouldBeNotNull {
16    async fn resolve_field(
17        &self,
18        ctx: &Context<'_>,
19        resolve: ResolveFut<'_>,
20    ) -> ServerResult<Option<Value>> {
21        match resolve.await {
22            Ok(None) => Ok(None),
23            // | Ok(Some(Value::Null)) => Err(MatcherError::new(
24            //   ctx.item.pos,
25            //   "Expected: not null\nReceived: null".to_string(),
26            // )),
27            Ok(Some(Value::Null)) => Err(ctx.set_error_path(
28                Error {
29                    message: "Expected: not null\nReceived: null".to_string(),
30                    source: Some(std::sync::Arc::new(MatcherError)),
31                    extensions: None,
32                }
33                .into_server_error(ctx.item.pos),
34            )),
35            Ok(Some(other)) => Ok(Some(other)),
36            Err(err) => Err(ctx.set_error_path(
37                Error {
38                    message: format!("Unexpected error occurred:\n\n{}", err.message),
39                    source: Some(std::sync::Arc::new(MatcherError)),
40                    extensions: None,
41                }
42                .into_server_error(ctx.item.pos),
43            )),
44        }
45    }
46}