我如何允许 graphql-ruby 提供骆驼案例的应用程序数据?

问题描述

我是 graphql-ruby 的新手,并且在查询从现有应用程序提供的驼峰数据时遇到问题。我试图在 graphql-ruby 跟踪器中搜索一些答案,但其中大多数都引用了突变,我在另一个方向上应用时遇到了麻烦。

应用程序中的大部分数据以蛇形外壳提供,并且运行良好。但是,由于某些用例早在我接受这个项目之前就已经存在,因此我们在某些领域发送了驼峰式数据。

当我将数据转换为蛇形情况时,解析器可以正常工作,但这似乎是一种可预见的情况,我猜有一个我没有看到的解决方案。

代码如下:

./graphql/types/user_notification_type.rb

module Types
  class UserNotificationType < Types::BaSEObject
    field :base_type,String,null: true # I've tried changing this to :baseType to no avail
    field :action_type,null: true
  end
end

./app/graphql/types/query_type.rb

module Types
  class QueryType < Types::BaSEObject
    field :notifications,[Types::UserNotificationType]
          null: true
          description: An array of user notifications

    # This doesn't work
    def notifications
      current_person_id = context[:current_person].id
      notifications = Resolvers::NotificationsResolver.new(current_person_id).notifications
 
      notifications
    end

    # But this works
    def notifications
      current_person_id = context[:current_person].id
      notifications = Resolvers::NotificationsResolver.new(current_person_id).notifications
 
      camel_case = notifications.dig(:alerts).map do |alert|   
        alert.transform_keys { |key| key.to_s.underscore }
      end
     
      camel_case
    end
  end
end

在这种情况下,Resolvers::NotificationsResolver.new(current_person_id).notifications 返回一个如下所示的数组:

[
  {
    baseType: "some string"
    actionPath: "some string"

  }
]

不起作用的情况为每个字段返回 null。有效的案例返回正确的值。但我宁愿不必为每种情况都运行这些转换。

告诉 graphql-ruby 它将提供驼峰数据并通过查询正确提供数据的最佳方法是什么?

在此先感谢您的帮助!

解决方法

来自 GraphQL Ruby 文档 [ 1 , 2 ]:

字段和参数名称应作为惯例用下划线表示。它们将在底层 GraphQL 类型中转换为驼峰式大小写,并在模式本身中转换为驼峰式大小写。

snake_cased 的参数将在 GraphQL 模式中骆驼化。使用示例:

field :posts,[PostType],null: false do
  argument :start_year,Int,required: true
end

相应的 GraphQL 查询将如下所示:

{
  posts(startYear: 2018) {
    id
  }
}

要禁用自动骆驼化,请将 camelize: false 传递给参数方法。

field :posts,required: true,camelize: false
end

此外,如果您的参数已经是驼峰式的,那么它将在 GraphQL 模式中保持驼峰式。但是,参数在传递给解析器方法时会被转换为snake_case:

field :posts,null: false do
  argument :startYear,required: true
end

def posts(start_year:)
  # ...
end

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...