Class: GraphQL::Client::HTTP
- Inherits:
-
Object
- Object
- GraphQL::Client::HTTP
- Defined in:
- lib/graphql/client/http.rb
Overview
Public: Basic HTTP network adapter.
GraphQL::Client::Client.new(
fetch: GraphQL::Client::HTTP.new("http://graphql-swapi.parseapp.com/")
)
Assumes GraphQL endpoint follows the express-graphql endpoint conventions.
https://github.com/graphql/express-graphql#http-usage
Production applications should consider implementing there own network adapter. This class exists for trivial stock usage and allows for minimal request header configuration.
Instance Attribute Summary collapse
-
#uri ⇒ Object
readonly
Public: Parsed endpoint URI.
Instance Method Summary collapse
-
#call(query) ⇒ Object
Public: Make an HTTP request for GraphQL query.
-
#headers(_) ⇒ Object
Public: Extension point for subclasses to set custom request headers.
-
#initialize(uri, &block) ⇒ HTTP
constructor
Public: Create HTTP adapter instance for a single GraphQL endpoint.
Constructor Details
#initialize(uri, &block) ⇒ HTTP
30 31 32 33 |
# File 'lib/graphql/client/http.rb', line 30 def initialize(uri, &block) @uri = URI.parse(uri) class_eval(&block) if block_given? end |
Instance Attribute Details
#uri ⇒ Object (readonly)
Public: Parsed endpoint URI
Returns URI.
38 39 40 |
# File 'lib/graphql/client/http.rb', line 38 def uri @uri end |
Instance Method Details
#call(query) ⇒ Object
Public: Make an HTTP request for GraphQL query.
Implements Client’s “fetch” adapter interface.
query - The GraphQL::Client::Query being sent
Returns { “data” => … , “errors” => … } Hash.
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/graphql/client/http.rb', line 56 def call(query) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = uri.scheme == "https" request = Net::HTTP::Post.new(uri.request_uri) request["Accept"] = "application/json" request["Content-Type"] = "application/json" headers(query).each { |name, value| request[name] = value } body = {} body["query"] = query.to_s body["variables"] = JSON.generate(query.variables) if query.variables.any? body["operationName"] = query.operation_name if query.operation_name request.body = JSON.generate(body) response = http.request(request) JSON.parse(response.body) end |
#headers(_) ⇒ Object
Public: Extension point for subclasses to set custom request headers.
query - The GraphQL::Client::Query being sent
Returns Hash of String header names and values.
45 46 47 |
# File 'lib/graphql/client/http.rb', line 45 def headers(_) {} end |