Attribute Macro async_graphql::Directive

source ·
#[Directive]
Expand description

Define a directive for query.

See also the Book.

§Macro attributes

AttributedescriptionTypeOptional
nameObject namestringY
name_typeIf true, the directive name will be specified from async_graphql::TypeName traitboolY
visibleIf false, it will not be displayed in introspection. See also the Book.boolY
visibleCall the specified function. If the return value is false, it will not be displayed in introspection.stringY
repeatableIt means that the directive can be used multiple times in the same location.boolY
rename_argsRename all the arguments according to the given case convention. The possible values are “lowercase”, “UPPERCASE”, “PascalCase”, “camelCase”, “snake_case”, “SCREAMING_SNAKE_CASE”.stringY
locationsSpecify the location where the directive is available, multiples are allowed. The possible values is “field”, …stringN

§Directive attributes

AttributedescriptionTypeOptional
nameArgument namestringY
descArgument descriptionstringY
defaultUse Default::default for default valuenoneY
defaultArgument default valueliteralY
default_withExpression to generate default valuecode stringY
validatorInput value validator See also the BookobjectY
visibleIf false, it will not be displayed in introspection. See also the Book.boolY
visibleCall the specified function. If the return value is false, it will not be displayed in introspection.stringY
secretMark this field as a secret, it will not output the actual value in the log.boolY

§Examples

use async_graphql::*;

struct ConcatDirective {
    value: String,
}

#[async_trait::async_trait]
impl CustomDirective for ConcatDirective {
    async fn resolve_field(&self, _ctx: &Context<'_>, resolve: ResolveFut<'_>) -> ServerResult<Option<Value>> {
        resolve.await.map(|value| {
            value.map(|value| match value {
                Value::String(str) => Value::String(str + &self.value),
                _ => value,
            })
        })
    }
}

#[Directive(location = "Field")]
fn concat(value: String) -> impl CustomDirective {
    ConcatDirective { value }
}

struct Query;

#[Object]
impl Query {
    async fn value(&self) -> &'static str {
        "abc"
    }
}

let schema = Schema::build(Query, EmptyMutation, EmptySubscription)
    .directive(concat)
    .finish();
let res = schema.execute(r#"{ value @concat(value: "def") }"#).await.into_result().unwrap().data;
assert_eq!(res, value!({
    "value": "abcdef",
}));