class EngagingNetworksRest::Client

Constants

ENS_DOMAIN

Attributes

api_key[R]
connection[R]
ens_auth_key[R]

Public Class Methods

new(api_key:) click to toggle source
# File lib/engaging_networks_rest/client.rb, line 12
def initialize(api_key:)
  @api_key = api_key

  @connection = Faraday.new(url: "https://#{ENS_DOMAIN}") do |conn|
    conn.request :json
    conn.response :json, :content_type => /\bjson$/

    conn.use Faraday::Response::Logger if ENV['DEBUG']
    conn.use EngagingNetworksRest::Response::RaiseError

    conn.adapter :net_http
  end
end

Public Instance Methods

authenticate!() click to toggle source
# File lib/engaging_networks_rest/client.rb, line 26
def authenticate!
  response = connection.post do |req|
    req.headers['Content-Type'] = 'application/json'
    req.url '/ens/service/authenticate'
    req.body = api_key
  end

  @ens_auth_key = response.body['ens-auth-token']
end
authenticated?() click to toggle source
# File lib/engaging_networks_rest/client.rb, line 36
def authenticated?
  !ens_auth_key.nil?
end
get(path:, params: {}) click to toggle source
# File lib/engaging_networks_rest/client.rb, line 40
def get(path:, params: {})
  request(method: :get, path: path, params: params)
end
post(path:, body: {}) click to toggle source
# File lib/engaging_networks_rest/client.rb, line 44
def post(path:, body: {})
  request(method: :post, path: path, body: body)
end

Private Instance Methods

request(method:, path:, params: {}, body: {}) click to toggle source
# File lib/engaging_networks_rest/client.rb, line 52
def request(method:, path:, params: {}, body: {})
  unless authenticated?
    authenticate!
  end

  response = connection.send(method) do |req|
    req.headers['Content-Type'] = 'application/json'
    req.path = path
    req.params = params
    req.headers['ens-auth-token'] = ens_auth_key
    req.body = ::JSON.generate(body) unless body.empty?
  end

  response.body
end