首页 > 解决方案 > 如何向 GraphQL Union 类型的 GraphQL 结构添加字段?(Rust 枚举和瞻博网络)

问题描述

我从Juniper GitBook复制了简单的 GraphQL Union 示例。

use juniper::{graphql_union, GraphQLObject};

// I copied the below from the Juniper Gitbook

#[derive(GraphQLObject)]
struct Human {
    id: String,
    home_planet: String,
}

#[derive(GraphQLObject)]
struct Droid {
    id: String,
    primary_function: String,
}

enum Character {
    Human(Human),
    Droid(Droid),
}

graphql_union!(Character: () where Scalar = <S> |&self| {
    instance_resolvers: |_| {
        &Human => match *self { Character::Human(ref h) => Some(h), _ => None },
        &Droid => match *self { Character::Droid(ref d) => Some(d), _ => None },
    }
});

这很好用。但后来我尝试在 GraphQLObject 结构中使用我的新字段。



// I added this type myself

#[derive(GraphQLObject)]
struct Movie {
    protagonist: Character,
    title: String,
}

这给了我一个奇怪的错误:

error[E0277]: the trait bound `Character: juniper::types::base::GraphQLType<__S>` is not satisfied
  --> src/main.rs:24:10
   |
24 | #[derive(GraphQLObject)]
   |          ^^^^^^^^^^^^^ the trait `juniper::types::base::GraphQLType<__S>` is not implemented for `Character`
   |
   = help: consider adding a `where Character: juniper::types::base::GraphQLType<__S>` bound
   = note: required because of the requirements on the impl of `juniper::types::base::GraphQLType<__S>` for `&Character`
   = note: required because of the requirements on the impl of `juniper::executor::IntoResolvable<'_, __S, &Character, _>` for `&Character`
   = note: required by `juniper::executor::IntoResolvable::into`

我不知道是怎么回事。我知道我的 Movie 结构的 GraphQLObject 语法是正确的。

标签: rustgraphqljuniper

解决方案


您需要添加where Scalar = <S>到您的graphql_union!定义中:

graphql_union!(Character: () where Scalar = <S> |&self| {
    instance_resolvers: |_| {
        &Human => match *self { Character::Human(ref h) => Some(h), _ => None },
        &Droid => match *self { Character::Droid(ref d) => Some(d), _ => None },
    }
});

这修复了错误。我在最新的 Gitbook 源代码大师中找到了这个。也许当前发布的文档已经过时了。


推荐阅读