简体   繁体   English

在 GraphQL 模式中获取上下文

[英]Get context inside a GraphQL schema

I'm using graphql-ruby and trying to protect admin's mutation in schema like that我正在使用 graphql-ruby 并试图保护管理员在这样的架构中的突变

class MySchema < GraphQL::Schema

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

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

end

but i don't have the context there.但我没有那里的上下文。 Also tried to do the same thing in Types::Admin::MutationType , same result.还尝试在Types::Admin::MutationType中做同样的事情,结果相同。

Is it possible to check out context anywhere before resolve?是否可以在解决之前在任何地方检查上下文?

One of the best if not the best guide that I found is here .我发现的最好的指南之一就是这里 It provides extensive documentation and guides.它提供了广泛的文档和指南。 Try using the self.visible?(ctx) method.尝试使用self.visible?(ctx)方法。 I also feel like you're fighting the gem instead of working with it.我也觉得你是在与宝石战斗而不是与它合作。 Try to restructure your code as outlined below.尝试按照以下概述重构您的代码。 It may be easier to work with.它可能更容易使用。

the context object doesn't get attached to the schema until the execute method is called on it.在调用execute方法之前, context object 不会附加到模式。 This usually happens in your 'app/controllers/graphql_controller.rb' file.这通常发生在您的“app/controllers/graphql_controller.rb”文件中。 So overall, you won't get to access the `context' object until your application executes your schema.所以总的来说,在您的应用程序执行您的模式之前,您将无法访问“上下文”object。 Since QueryType and MutationType get attached to it after you may want to do the following assuming you used the built in code generation tool.由于 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

test it out using the following graphql query (I use apollo for chrome)使用以下 graphql 查询对其进行测试(我使用 apollo for chrome)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM