Class: Yogurt::Http
- Inherits:
-
Object
- Object
- Yogurt::Http
- Extended by:
- T::Sig
- Includes:
- QueryExecutor
- Defined in:
- lib/yogurt/http.rb
Instance Method Summary collapse
- #connection ⇒ Object
- #execute(query, operation_name:, variables: nil, options: nil) ⇒ Object
- #headers(options) ⇒ Object
-
#initialize(uri, headers: {}) ⇒ Http
constructor
A new instance of Http.
- #options_type_alias ⇒ Object
Constructor Details
#initialize(uri, headers: {}) ⇒ Http
Returns a new instance of Http.
14 15 16 17 18 19 20 21 22 23 |
# File 'lib/yogurt/http.rb', line 14 def initialize(uri, headers: {}) parsed = URI.parse(uri) if parsed.is_a?(URI::HTTP) || parsed.is_a?(URI::HTTPS) @uri = T.let(parsed, T.any(URI::HTTP, URI::HTTPS)) else raise ArgumentError, "Invalid URI: #{uri} (must be HTTP or HTTPS)" end @headers = T.let(headers, T::Hash[String, String]) end |
Instance Method Details
#connection ⇒ Object
73 74 75 76 77 78 |
# File 'lib/yogurt/http.rb', line 73 def connection client = Net::HTTP.new(@uri.host, @uri.port) client.use_ssl = @uri.scheme == "https" client end |
#execute(query, operation_name:, variables: nil, options: nil) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/yogurt/http.rb', line 45 def execute(query, operation_name:, variables: nil, options: nil) request = Net::HTTP::Post.new(@uri.request_uri) request.basic_auth(@uri.user, @uri.password) if @uri.user || @uri.password request["Accept"] = "application/json" request["Content-Type"] = "application/json" headers().each do |name, value| request[name] = value end body = T.let({}, T::Hash[String, T.untyped]) body["query"] = query body["variables"] = variables if variables&.any? body["operationName"] = operation_name request.body = JSON.generate(body) response = connection.request(request) case response when Net::HTTPOK, Net::HTTPBadRequest JSON.parse(response.body) else { "errors" => [{ "message" => "#{response.code} #{response.}" }] } end end |
#headers(options) ⇒ Object
27 28 29 |
# File 'lib/yogurt/http.rb', line 27 def headers() @headers end |
#options_type_alias ⇒ Object
33 34 35 |
# File 'lib/yogurt/http.rb', line 33 def T.type_alias {T.untyped} end |