【问题标题】:Unable to implement a union in GraphQL无法在 GraphQL 中实现联合
【发布时间】:2020-12-19 03:42:45
【问题描述】:

我已经阅读了多篇关于处理错误的文章,尤其是https://blog.logrocket.com/handling-graphql-errors-like-a-champ-with-unions-and-interfaces/。虽然,我无法理解为什么我无法在我的代码中使用联合,或者需要什么方法来实现它。

联合原因

我希望返回自定义错误。例如,如果用户电子邮件已经存在,则返回错误消息,例如

{ message: "Email already exists", key: "EMAIL_EXISTS" }

类型

const UserType = new GraphQLObjectType({
    name: 'User',
    fields: () => ({
        id: { type: GraphQLInt },
        email: { type: GraphQLString }
    })
});

const AuthType = new GraphQLObjectType({
    name: 'Auth',
    fields: () => ({
        token: { type: GraphQLString },
        user: { type: UserType }
    })
});

const UserNotFound = new GraphQLObjectType({
    name: 'UserNotFound',
    fields: () => ({
        message: { type: GraphQLString },
        key: { type: GraphQLString }
    })
});

union AuthUserType = AuthType | UserNotFound

module.exports = {
    UserType,
    AuthType,
    AuthUserType
};

为了完成这项工作,我需要做些什么特别的事情吗?

感谢您在这方面提供的所有帮助以及如何实施联合。

【问题讨论】:

    标签: graphql express-graphql


    【解决方案1】:

    这似乎是我一直在寻找的解决方案。虽然我遇到了不同的问题,但在 graphiql 终端中,它按预期工作。

    const AuthResultType = new GraphQLUnionType({
        name: 'AuthResult',
        types: [ AuthType, AuthTypeError ],
        resolveType(value) {
            console.log('THE VAKLUE IS', value);
            if (value.token) {
                return AuthType;
            } else if (value.message) {
                return AuthTypeError;
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 2021-11-30
      • 2019-07-02
      • 1970-01-01
      • 2020-07-15
      • 2023-01-20
      • 2016-06-15
      • 2020-01-08
      • 2020-04-11
      相关资源
      最近更新 更多