module PreactRpcClient

A module that wraps socket server interaction with the preact-rpc server

Attributes

data_end_marker[RW]
server_host[RW]
server_port[RW]
socket_file[RW]
socket_type[RW]

Public Class Methods

configure() { |self| ... } click to toggle source
# File lib/preact_rpc_client.rb, line 15
def configure
  yield self
  @sock = nil
end

Public Instance Methods

render_component(component_name, props) click to toggle source

Render function

# File lib/preact_rpc_client.rb, line 22
def render_component(component_name, props)
  # Construct payload JSON
  payload = {
    id: next_request_id,
    component: component_name,
    props: props,
  }.to_json + @data_end_marker

  # Send request to server
  conn.send(payload, 0)

  # Receive response
  resp = ""
  while true
    val = conn.recv(@max_data_buffer_size)
    is_end = val.match(@data_end_marker)
    val = val.split(@data_end_marker).first if is_end
    resp += val
    break if is_end
  end

  # Parse JSON response and return
  begin
    return JSON.parse(resp)
  rescue
    return {
      error: 'Invalid server response'
    }
  end
end

Private Instance Methods

conn() click to toggle source
# File lib/preact_rpc_client.rb, line 55
def conn
  if @socket_type == 'unix'
    @sock ||= UNIXSocket.new @socket_file
  else
    @sock ||= TCPSocket.new @server_host, @server_port
  end
  return @sock
end
next_request_id() click to toggle source
# File lib/preact_rpc_client.rb, line 64
def next_request_id
  @req_id ||= 0
  @req_id += 1
end