【问题标题】:Get context inside a GraphQL schema在 GraphQL 模式中获取上下文
【发布时间】:2019-10-31 07:15:38
【问题描述】:

我正在使用 graphql-ruby 并试图保护管理员在这样的架构中的突变

class MySchema < GraphQL::Schema

  mutation(Types::Admin::MutationType) if context[:current_user].admin?

  mutation(Types::MutationType)
  query(Types::QueryType)

end

但我没有那里的上下文。 也尝试在Types::Admin::MutationType 中做同样的事情,同样的结果。

是否可以在解决之前在任何地方检查上下文?

【问题讨论】:

    标签: ruby-on-rails ruby graphql graphql-ruby


    【解决方案1】:

    我发现的最好的指南之一是here。它提供了广泛的文档和指南。尝试使用self.visible?(ctx) 方法。我也觉得你是在与宝石战斗而不是与它一起工作。尝试按照以下概述重构您的代码。它可能更容易使用。

    context 对象在调用 execute 方法之前不会附加到架构。这通常发生在您的“app/controllers/graphql_controller.rb”文件中。所以总的来说,在您的应用程序执行您的模式之前,您将无法访问“上下文”对象。由于 QueryType 和 MutationType 在您使用内置代码生成工具后可能需要执行以下操作。

    
    # '/app/graphql/my_schema.rb'
    
    class MySchema < GraphQL::Schema
      mutation(Types::MutationType)
      query(Types::QueryType)
    end
    
    # '/app/graphql/types/mutation_type.rb'
    class Types::MutationType < Types::BaseObject
      field :some_admin_mutation, mutation: Mutations::Admin::SomeAdminMutation
    end
    
    
    # '/app/graphql/mutations/admin/some_admin_mutation.rb'
    class Mutations::Admin::SomeAdminMutation < Mutations::BaseMutation
      ...
    
       # using this class method, you can choose to hide certain mutations
       def self.visible?(context)
          context[:current_user].admin?
       end
    end
    

    使用以下 graphql 查询对其进行测试(我使用 apollo for chrome)

    {
      __schema {
        mutationType {
          name
          fields {
            name
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 2018-11-22
      • 1970-01-01
      • 2014-11-29
      • 2020-11-16
      • 2020-04-13
      • 2019-07-07
      • 2018-07-15
      • 2020-06-01
      相关资源
      最近更新 更多