class SmeeClient

The main Smee client class

Public Class Methods

create_channel() click to toggle source
# File lib/smee.rb, line 9
def self.create_channel
  response = HTTParty.head('https://smee.io/new', follow_redirects: false)
  response.headers['location']
end
new(source:, target:) click to toggle source
# File lib/smee.rb, line 14
def initialize(source:, target:)
  @source = source
  @target = URI.parse(target)
end

Public Instance Methods

close() click to toggle source
# File lib/smee.rb, line 24
def close
  puts '[SmeeClient]: Closing connection'
  @events.close
end
start() click to toggle source
# File lib/smee.rb, line 19
def start
  puts "[SmeeClient]: Listening for events at #{@source}"
  subscribe
end

Private Instance Methods

copy_headers(json) click to toggle source
# File lib/smee.rb, line 55
def copy_headers(json)
  headers = {
    'Content-Type': 'application/json'
  }

  # Don't want to include these as headers
  json.delete 'body'
  json.delete 'query'

  json.each do |key, value|
    # We need to ensure that headers are strings
    headers[key] = value.to_s
  end

  headers
end
handle_event(event) click to toggle source
# File lib/smee.rb, line 43
def handle_event(event)
  json = JSON.parse event.data
  return unless json.key?('body')

  body = json['body']
  query = json['query']

  headers = copy_headers(json)

  post(body, query, headers)
end
post(body, query, headers) click to toggle source
# File lib/smee.rb, line 72
def post(body, query, headers)
  # Send an HTTP request
  response = HTTParty.post(@target, {
    query: query,
    body: body.to_json,
    headers: headers
  })

  puts "[SmeeClient]: Pushed event, response: #{response.body}"
end
subscribe() click to toggle source
# File lib/smee.rb, line 31
def subscribe
  @events = SSE::Client.new(@source) do |client|
    client.on_event do |event|
      handle_event event
    end

    client.on_error do |error|
      puts "Error: #{error}"
    end
  end
end