-1

I've been reading multiple articles in regards to handling errors especially https://blog.logrocket.com/handling-graphql-errors-like-a-champ-with-unions-and-interfaces/. Although, I'm unable to understand why I'm unable to use a union within my code or what approach is needed to implement it.

Reason for Union

I wish to return a custom error. For example if a user email already exists, return an error message such as

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

Is there something special I would need to do in order to make this work?

Thank you for all the help on this one and how to implement a union.

Yama
  • 401
  • 1
  • 8
  • 22

1 Answers1

0

This seems to be the solution to what I've been trying to find. Although I've run into a different problem, within the graphiql terminal, it works as expected.

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;
        }
    }
});
Yama
  • 401
  • 1
  • 8
  • 22