在GraphQLruby中的任何查询之前运行函数



我想在GraphQL上运行任何查询之前先运行一个函数。我想控制一些条件,并抛出GraphQL::ExecutionError,以防它捕捉到错误。我知道有一个基本查询在任何查询之前运行,但它需要检查用户是否登录以运行查询,在这里抛出错误会停止执行,我认为放置它的位置是否正确。如何在进行任何查询之前执行函数?这就是我目前所尝试的:

module Queries
class BaseQuery < GraphQL::Schema::Resolver
def authorized?(**args)
if context[:current_user].nil?
raise GraphQL::ExecutionError, "Only logged users can run this query"
elsif context[:current_user].orders.any?

today_created = false
not_updated = false
context[:current_user].orders.each do |sp|
if sp.time_opened.to_date == Date.today.to_date
today_created = true
end
if sp.time_opened.to_date != Date.today.to_date && sp.time_closed == nil
not_updated = true
end
end
if (today_created == false && not_updated == false)
# raise GraphQL::ExecutionError, "Error"
end
true
else
# Return true to continue the query:
true
end
end
end
end

您不应该在BaseQuery中运行这样的代码

if context[:current_user].nil?
raise GraphQL::ExecutionError, "Only logged users can run this query"

而不是使用gem进行授权。例如action_policy对GraphQL 有很好的支持

if (today_created == false && not_updated == false)
# raise GraphQL::ExecutionError, "Error"
end

如果您需要为每个请求检查此项,请使用BaseResolver

因此,你应该为你的代码使用其他应用层

最新更新