[ Rails ] 如果无法确定在 graphql-ruby 中哪里出现了性能问题

請問有什麼問題嗎?

使用GraphQL时,是模型方面慢还是GraphQL类型方面慢?而且,如果层次更深,很难确定。

解决 (jiě jué)

 

在公式文件中没有详细的解释,但是

 

在这个博客中,有一段能够很好地输出到日志的代码。

在 platform_trace 中计算执行时间并传递给 observe,然后可以在那里记录日志或执行其他操作。

class MyCustomTracer < GraphQL::Tracing::PlatformTracing
  self.platform_keys = {
    "lex" => "graphql.lex",
    "parse" => "graphql.parse",
    "validate" => "graphql.validate",
    "analyze_multiplex" => "graphql.analyze_multiplex",
    "analyze_query" => "graphql.analyze_query",
    "execute_multiplex" => "graphql.execute_multiplex",
    "execute_query" => "graphql.execute_query",
    "execute_query_lazy" => "ygraphql.execute_query_lazy",
    "execute_field" => "graphql.execute_field",
    "execute_field_lazy" => "ygraphql.execute_field_lazy",
    "authorized" => "graphql.authorized",
    "authorized_lazy" => "graphql.authorized_lazy",
    "resolve_type" => "graphql.resolve_type",
    "resolve_type_lazy" => "graphql.resolve_type_lazy",
  }

  def platform_trace(platform_key, key, _data, &block)
    start = ::Process.clock_gettime ::Process::CLOCK_MONOTONIC
    result = block.call
    duration = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - start
    observe(platform_key, key, duration)
    result
  end

  def platform_field_key(type, field)
    "graphql.#{type.graphql_name}.#{field.graphql_name}"
  end

  def platform_authorized_key(type)
    "graphql.authorized.#{type.graphql_name}"
  end

  def platform_resolve_type_key(type)
    "graphql.resolve_type.#{type.graphql_name}"
  end

  def observe(platform_key, key, duration)
    return if key == "authorized"

    Rails
      .logger.debug "platform_key: #{platform_key}, key: #{key}, duration: #{(duration * 1000).round(5)} ms"
  end
end

tracer(MyCustomTracer.new)

最初的代码是什么

def observe(platform_key, key, duration)
  return if key == 'authorized'

  puts "platform_key: #{platform_key}, key: #{key}, duration: #{(duration * 1000).round(5)} ms".yellow
end

在 https://github.com/sickill/rainbow 裡,缺少 “yellow” 導致錯誤,我猜應該要安裝這個才行。

# https://github.com/sickill/rainbow#refinement
require 'rainbow/refinement'
using Rainbow
puts "Hi!".green
广告
将在 10 秒后关闭
bannerAds