3

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?

4

2 回答 2

2

这个问题的答案其实很简单。如果你想从突变返回不同的类型,在我的例子中是上面的 RegistrationPayloadType。

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

      payload_type RegistrationPayloadType

      ...
    end

使用 payload_type 类方法得到了我需要的东西。

于 2020-01-03T11:03:42.140 回答
-1

这个博客(https://www.abhaynikam.me/posts/polymorphic-types-with-graphql-ruby/)介绍了如何在 GraphQL-ruby 中将联合类型用于多态类型。在这里,不是使用payload_type另一个字段 Type 而是返回解析联合类型。

于 2020-03-08T13:26:36.293 回答