Sha256: 813c93bd201dfba573b0c418f0b98eb86c69e2e174264948cc69151daf798bec

Contents?: true

Size: 1.84 KB

Versions: 1

Compression:

Stored size: 1.84 KB

Contents

module Bearcat
  class GraphqlError < StandardError
    attr_reader :response

    def initialize(message, response: nil)
      super(message)
      @response = response
    end
  end

  class Client < Footrest::Client
    # Request body format should be:
    #  - { query: "query string" }
    #  - "query string"
    #  - "path/to/gql/file", may be absolute, relative to application root, or relative to `app/graphql`. `.gql` extension is optional.
    module GraphQL
      def graphql_query(query, args = {})
        if query.is_a?(String)
          if /\A\w+\Z/.match?(query) && !query.include?("{")
            query = query.underscore
            @@gql_cache ||= {}

            query = cache_on_class("gql:#{query}") do
              paths = []

              pn = Pathname.new(query)
              if pn.absolute?
                paths << query
              else
                paths << Rails.root.join("app", "graphql", query)
                paths << Rails.root.join(query)
              end

              paths = paths.flat_map do |path|
                [path, "#{path}.gql"]
              end

              query = paths.find do |path|
                File.exist?(path)
              end

              File.read(query)
            end
          end

          args.symbolize_keys!

          query = query.gsub(/\{\{(.*?)\}\}/) do |_m|
            match = Regexp.last_match
            key = match[1].strip.to_sym
            args[key]
          end

          query = {
            query: query
          }
        end

        result = post('/api/graphql', query)
        raise GraphqlError.new("Error running GraphQL query:\n#{result["errors"].to_json}", response: result) if result["errors"].present?

        # TODO: It'd be nice to unwrap and return result["data"] directly, but we want to keep backwards compatibility
        result
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bearcat-1.5.37 lib/bearcat/client/graph_ql.rb