Class: Mylk::HTTP
Overview
HTTP client for the SurrealDB
Instance Attribute Summary
Attributes inherited from Base
#database, #namespace, #password, #uri, #username
Instance Method Summary collapse
- #connect ⇒ Object
- #disconnect ⇒ Object
-
#execute(query) ⇒ Object
rubocop:disable Metrics/AbcSize.
-
#initialize(url) ⇒ HTTP
constructor
A new instance of HTTP.
Methods inherited from Base
Constructor Details
#initialize(url) ⇒ HTTP
Returns a new instance of HTTP.
12 13 14 15 16 17 18 |
# File 'lib/mylk/http.rb', line 12 def initialize(url) super @connection = Net::HTTP.new(uri.host, uri.port) # Mutex to prevent multiple threads from using the same connection @mutex = Mutex.new end |
Instance Method Details
#connect ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/mylk/http.rb', line 20 def connect return true if connected? @mutex.synchronize do @connection.start @connected = true end # Ping the server to check if the connection is established execute("INFO FOR DB").success? rescue Error disconnect end |
#disconnect ⇒ Object
34 35 36 37 38 39 40 41 |
# File 'lib/mylk/http.rb', line 34 def disconnect return if disconnected? @mutex.synchronize do @connection.finish @connected = false end end |
#execute(query) ⇒ Object
rubocop:disable Metrics/AbcSize
43 44 45 46 47 48 49 50 51 52 |
# File 'lib/mylk/http.rb', line 43 def execute(query) # rubocop:disable Metrics/AbcSize connect if disconnected? request = Net::HTTP::Post.new(uri.path, headers).tap { |r| r.body = query } response = @mutex.synchronize { @connection.request(request) } raise Error, format_error(response) unless (200..300).include?(response.code.to_i) Response.new(parse_json_body(response).first) end |