Class: Mylk::WebSocket

Inherits:
Base
  • Object
show all
Defined in:
lib/mylk/websocket.rb

Overview

WebSocket client for the SurrealDB

Constant Summary collapse

WAIT_SLEEP_DURATION =

1 millisecond

0.001
CONNECTION_TIMEOUT =

2 seconds

2
REQUEST_TIMEOUT =

2 seconds

2

Instance Attribute Summary

Attributes inherited from Base

#database, #namespace, #password, #uri, #username

Instance Method Summary collapse

Methods inherited from Base

#connected?, #disconnected?

Constructor Details

#initialize(url) ⇒ WebSocket

Returns a new instance of WebSocket.



14
15
16
17
18
19
20
21
# File 'lib/mylk/websocket.rb', line 14

def initialize(url)
  super

  @connection = nil
  # Mutex to synchronize the access to the requests hash
  @mutex = Mutex.new
  @requests = {}
end

Instance Method Details

#connectObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mylk/websocket.rb', line 23

def connect
  @connection = ::WebSocket::Client::Simple.connect(uri.to_s, headers: headers)

  attach_on_message_handler
  wait_for_connection_establishment

  @connected = true

  # Authenticate and select the database
  call_rpc("signin", [{ user: username, pass: password }])
  call_rpc("use", [namespace, database])

  # Ping the server to check if the connection is established
  execute("INFO FOR DB").success?
end

#disconnectObject



39
40
41
42
43
44
# File 'lib/mylk/websocket.rb', line 39

def disconnect
  return if disconnected?

  @connection.close
  @connected = false
end

#execute(query) ⇒ Object



46
47
48
# File 'lib/mylk/websocket.rb', line 46

def execute(query)
  Response.new(call_rpc("query", [query]))
end