class Bifrost::Client

Constants

VERSION

Attributes

bifrost_server_url[R]
jwt_secret[R]

Public Class Methods

new(jwt_secret: ENV["JWT_SECRET"], bifrost_server_url: ENV["BIFROST_URL"]) click to toggle source
# File lib/bifrost/client.rb, line 10
def initialize(jwt_secret: ENV["JWT_SECRET"], bifrost_server_url: ENV["BIFROST_URL"])
  @jwt_secret = jwt_secret
  @bifrost_server_url = bifrost_server_url
end

Public Instance Methods

broadcast(channel, event:, data: nil) click to toggle source
# File lib/bifrost/client.rb, line 15
def broadcast(channel, event:, data: nil)
  data = {
    channel: channel,
    message: {
      event: event,
      data: data
    },
    exp: Time.now.to_i + 60
  }
  jwt = JWT.encode(data, jwt_secret, "HS512")
  uri = URI.parse(bifrost_server_url)
  uri.path = "/broadcast"
  ssl = uri.is_a?(URI::HTTPS)

  res = Net::HTTP.start(uri.host, uri.port, use_ssl: ssl) do |http|
    request                 = Net::HTTP::Post.new(uri.path)
    request.body            = JSON.dump(token: jwt)
    request["Content-Type"] = "application/json"
    http.request(request)
  end

  if Integer(res.code) > 206
    raise ServerError.new("Bifrost server responded with #{res.code}: #{res.body}")
  else
    JSON.parse(res.body, symbolize_names: true)
  end
end
token_for(channels:) click to toggle source
# File lib/bifrost/client.rb, line 43
def token_for(channels:)
  payload = { channels: channels, exp: Time.now.to_i + 60 }
  JWT.encode(payload, jwt_secret, "HS512")
end