0
votes

Hi I'm trying to figure out how to handle user errors with graphql and relay when executing mutations.

That's my graphql implementation for a createUser mutation:

mutationWithClientMutationId({
  name: 'CreateUser',
  inputFields: {
    email: { type: new GraphQLNonNull(GraphQLString) },
  },
  outputFields: {
    user: { type: userType },
    error: {type: errorType},
  },
  mutateAndGetPayload: async (attrs, { viewer }) => {
    try {
      // Try to create a user
    } catch(err) {
      // err.toObject has the shape required by the error type
      return { error: err.toObject() };
    }
  }
});

And this is my relay mutation class

class CreateUserMutation extends Relay.Mutation {
  getMutation() {
    return Relay.QL`mutation { createUser }`;
  }

  getVariables() {
    return {
      email: this.props.email,
    };
  }

  getFatQuery() {
    return Relay.QL`
      fragment on CreateUserPayload {
        error
      }
    `;
  }

  getConfigs() {
    return [{
      type: "FIELDS_CHANGE",
      fieldIDs: {
        error: ????,
      }
    }];
  }
}

I have tried also another approach which is to not catch the error in graphql, and listen on onFailure when executing a relay mutation but I had to do something like that to get my error return error.getError().source.errors[0] but I think I like the approach of returning an error type better but I cant get it to work, any help please

1

1 Answers

0
votes

I was able to get the error using REQUIRED_CHILDRED instead of FIELDS_CHANGE.

that's what I ended up doing

class CreateUserMutation extends Relay.Mutation {
  getMutation() {
    return Relay.QL`mutation { createUser }`;
  }

  getVariables() {
    return {
      email: this.props.email,
    };
  }

  getFatQuery() {
    return Relay.QL`
      fragment on CreateUserPayload {
        error
      }
    `;
  }

  getConfigs() {
    return [{
      type: "REQUIRED_CHILDREN",
      children: [
        Relay.QL`
          fragment on CreateUserPayload {
            error {
              message
            }
          }
        `
      ]
    }];
  }
}