无法在GraphQL中实现联合

问题描述

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

加入联盟的原因

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

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

TYPE

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
};

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

感谢您在此方面的所有帮助以及如何实现工会。

解决方法

这似乎是我一直试图找到的解决方案。尽管我遇到了另一个问题,但是在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;
        }
    }
});

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...