lib/bearcat/client/graph_ql.rb in bearcat-1.5.36 vs lib/bearcat/client/graph_ql.rb in bearcat-1.5.37
- old
+ new
@@ -1,17 +1,67 @@
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" }. More info in README.md
+ # 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)
+ 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
- post('/api/graphql', 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
\ No newline at end of file