Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a Union type from a GraphQL Mutation

Tags:

graphql-ruby

I want to use this pattern for returning validation failures from the GraphQL Ruby: https://medium.com/@sachee/200-ok-error-handling-in-graphql-7ec869aec9bc

From my mutation I'd like to be able to return a payload that is a union like this:

    class RegistrationPayloadType < Base::Union
      possible_types UserType, ValidationFailureType

      def self.resolve_type(object, context)
        if context.current_user.present?
          UserType
        else
          ValidationFailureType
        end
      end
    end

And my resolve method in the mutation is something like this;

      def resolve(input:)
        @input = input.to_h

        if registration.save
          candidate
        else
          registration.errors
        end
      end

The client can then call the mutation thus;

  mutation UserRegistrationMutation($input: UserRegistrationInput!) {
    userRegistration(input: $input) {
      __typename
      ... on User {
        id
      }
      ... on ValidationFailure {
        path
        message
      }
    }
  }

How in GraphQL-ruby can I return a Union as a payload?

like image 858
james2m Avatar asked Nov 19 '25 12:11

james2m


1 Answers

The answer to this was actually really simple. If you want to return a different type from the mutation, in my case the RegistrationPayloadType above.

    class RegistrationMutation < Base::Mutation
      argument :input, Inputs::RegistrationInputType, required: true

      payload_type RegistrationPayloadType

      ...
    end

Using the payload_type class method got me what I needed.

like image 55
james2m Avatar answered Nov 22 '25 04:11

james2m