0

I want to run a function before any query I run on GraphQL. I want to control some condition and throw a GraphQL:: ExecutionError in case it catches the error. I know there is a base query that runs before any query but it is needed to check if a user is logged in or not to run the queries and throwing error here stops the execution and I don't think if the right place to put it on. How can I execute a function before any query I made? This.is what I tried so far:

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


D. Lawrence
  • 943
  • 1
  • 10
  • 23
john bowlee
  • 125
  • 1
  • 11

1 Answers1

0

You should not run such code in BaseQuery

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

Instead of this use gem for authorization. For example action_policy have good support for GraphQL

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

If you need to check this for every request use BaseResolver

Thus you should use other app layers for your code

mechnicov
  • 12,025
  • 4
  • 33
  • 56