Ruby graphql 解析器替代方案:方法挂钩 --- 它是如何工作的?

Ruby graphql resolver alternative: method hooking --- how does it work?

我需要将自定义字段添加到 graphql 响应中,因此我考虑实现自己的自定义解析器。但是看到 this,我问自己是否真的需要自定义解析器:

First, ask yourself ... Do you really need a Resolver? Putting logic in a Resolver has some downsides:

  • Since it's coupled to GraphQL, it's harder to test than a plain ol' Ruby object in your app
  • Since the base class comes from GraphQL-Ruby, it's subject to upstream changes which may require updates in your code

好吧,我完全同意。但是我不明白下面的替代方法是如何工作的。

Here are a few alternatives to consider:

  • Put display logic (sorting, filtering, etc.) into a plain ol' Ruby class in your app, and test that class
  • Hook up that object with a method, for example:
field :recommended_items, [Types::Item], null: false
def recommended_items
  ItemRecommendation.new(user: context[:viewer]).items
end

不幸的是,这对我来说似乎并不明显。

我有一个 Request 模型与 Messageshas_many 关系。

def Request
   has_many :messages, -> { order(created_at: :desc, id: :desc) }

   def unread_message_count(user)
    return messages.unread(user).count
  end
end

我想将 unread_message_count 字段添加到 graphql RequestType 但我迷路了:

class RequestType < Types::BaseObject
  field :unread_message_count, Integer, null: false

  def unread_message_count
    user = context[:current_user]
    // here
  end
end

OK,很简单,你可以参考实际模型中的graphql类型使用Types::BaseObject#object方法

所以在这种情况下,它是:

class RequestType < Types::BaseObject
  field :unread_message_count, Integer, null: false

  def unread_message_count
    user = context[:current_user]
    user.nil? ? 0 : object.unread_message_count(user)
  end
end