lib/swarmclient/communication.rb in swarmclient-0.1.0 vs lib/swarmclient/communication.rb in swarmclient-0.1.1
- old
+ new
@@ -1,11 +1,10 @@
-require 'faye/websocket'
-require 'eventmachine'
require 'websocket-client-simple'
+require 'eventmachine'
require 'json'
-DEFAULT_IP = '127.0.0.1'
+DEFAULT_IP = 'ws://127.0.0.1'
DEFAULT_PORT = 8080
module Swarmclient
class Communication
@@ -26,12 +25,16 @@
def read key
send cmd: 'read', data: { key: key }
end
+ def read_multiple keys
+ send_multiple cmd: 'read', keys: keys
+ end
+
def update key, value
- send cmd: 'update', data: { key: key }
+ send cmd: 'update', data: { key: key, value: value }
end
def remove key
send cmd: 'delete', data: { key: key }
end
@@ -44,10 +47,17 @@
send cmd: 'keys', data: nil
end
private
+ def send_multiple cmd:, keys:
+ keys.map do |key|
+ res = send cmd: cmd, data: { key: key }
+ Hash[key, res ? res[:value] : nil]
+ end
+ end
+
def send cmd:, data:
endpoint, req = [
[@_endpoint, ':', @_port.to_s].join(''),
{ "bzn-api": "crud", "cmd": cmd, "data": data, "db-uuid": @_uuid, "request-id": rand(@req_id_range) }
@@ -71,11 +81,11 @@
return res[:error]
when nil
- return res
+ return res[:data]
else
return res[:error]
@@ -87,31 +97,35 @@
def get req:, endpoint:
res, err = [nil, nil]
- EventMachine.run do
+ begin
+ EventMachine.run do
- ws = WebSocket::Client::Simple.connect endpoint
+ ws = WebSocket::Client::Simple.connect endpoint
- ws.on :message do |msg|
- res = msg.data
- EventMachine::stop_event_loop
- end
+ ws.on :message do |msg|
+ res = msg.data
+ EventMachine::stop_event_loop
+ end
- ws.on :open do
- ws.send req.to_json
- end
+ ws.on :open do
+ ws.send req.to_json
+ end
- ws.on :close do |e|
- EventMachine::stop_event_loop
- end
+ ws.on :close do |e|
+ EventMachine::stop_event_loop
+ end
- ws.on :error do |e|
- err = e
- EventMachine::stop_event_loop
- end
+ ws.on :error do |e|
+ err = e
+ EventMachine::stop_event_loop
+ end
+ end
+ rescue => e
+ err = e
end
[err, res]
end