Ruby graphql Как определить тип объекта, который не является Active Record? - PullRequest
1 голос
/ 06 августа 2020

Я хочу создать MentionType, которого нет в ActiveRecord. И при запросе SummaryCommentType я хочу вернуть MentionType вместе с ним. Но я не знаю, как это сделать.

Я совершенно новичок в graphql. Извините за мой engli sh.

Вот мой код

module Types
  class MentionType < Types::BaseObject
    field :id, Integer, null: false  
    field :name, String, null: false
  end
end








module Types
 class SummaryCommentType < Types::BaseObject
  field :id, Integer, null: false
  field :summary_id, Integer, null: false
  field :comment_status, Integer, null: false
  field :curator_id, Integer, null: true
  field :curator, CuratorType, null: true
  field :total_like, Integer, null: true
  field :total_dislike, Integer, null: true
  field :comment_desc, String, null: true
  field :parent_comment_key, Integer, null: true
  field :created_at, GraphQL::Types::ISO8601DateTime, null: true
  field :updated_at, GraphQL::Types::ISO8601DateTime, null: true
  field :sub_comment_count, Integer, null: true
  field :summary_comment_sticker, SummaryCommentStickerType, null: true 
  field :mention, [MentionType.graphql_definition], null:true do
    argument :comment_id, Integer, required: true
  end

  def mention(comment_id:)
    comment = SummaryComment.where(id: self.object.id)
    #  to do put logic here to query mention by comment
    #  ....

    return mention
  end

 end
end

1 Ответ

0 голосов
/ 14 августа 2020

Объекты, возвращаемые из запроса GraphQL, не обязательно должны быть объектами ActiveRecord, им просто нужны методы, которые сопоставляются с вашими именами полей, или ваши поля должны иметь методы, которые могут извлекать необходимые данные из объекта.

Вот пример, в котором используются несколько различных способов приведения к типу:

module Types
  class MentionType < BaseObject
    field :id, Integer, null: false
    field :name, String, null: false
    field :name_upper, String, null: false
    def name_upper
      if object.is_a?(Hash)
        object[:name].upcase
      else
        object.name.upcase
      end
    end
  end
end

module Types
  class QueryType < Types::BaseObject
    field :mentions, [MentionType], null: true

    def mentions
      [
        Struct.new(:id, :name).new(1, 'Struct'),
        OpenStruct.new(id: 2, name: 'OpenStruct'),
        { id: 3, name: 'Hash' },
        CustomObject.new(id: 4, name: 'CustomObject'),
      ]
    end

    class CustomObject
      def initialize(attrs)
        @attrs = attrs
      end

      def id
        @attrs[:id]
      end

      def name
        @attrs[:name]
      end
    end
  end
end

Запрос:

query {
  mentions {
    id
    name
    nameUpper
  }
}

Результат:

{
  "data": {
    "mentions": [
      {
        "id": 1,
        "name": "Struct",
        "nameUpper": "STRUCT"
      },
      {
        "id": 2,
        "name": "OpenStruct",
        "nameUpper": "OPENSTRUCT"
      },
      {
        "id": 3,
        "name": "Hash",
        "nameUpper": "HASH"
      },
      {
        "id": 4,
        "name": "CustomObject",
        "nameUpper": "CUSTOMOBJECT"
      }
    ]
  }
}
...