Class: Audiosocket::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/audiosocket/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.


10
11
12
13
14
15
16
17
18
19
20
# File 'lib/audiosocket/client.rb', line 10

def initialize options = {}
  @url = options[:url] || "https://api.audiosocket.com/v5"

  @conn = Faraday.new url: @url do |f|
    f.request :json
    f.adapter Faraday.default_adapter
  end

  @conn.headers["X-Audiosocket-Token"] =
    options.values_at(:token, :uid).compact.join ":"
end

Instance Attribute Details

#connObject (readonly)

Returns the value of attribute conn.


7
8
9
# File 'lib/audiosocket/client.rb', line 7

def conn
  @conn
end

#urlObject (readonly)

Returns the value of attribute url.


8
9
10
# File 'lib/audiosocket/client.rb', line 8

def url
  @url
end

Instance Method Details

#auth(email_or_token, password = nil) ⇒ Object

Auth a user given a temporary token or email and password.


24
25
26
27
# File 'lib/audiosocket/client.rb', line 24

def auth email_or_token, password = nil
  password ? post("auth", email: email_or_token, password: password) :
    post("auth/#{email_or_token}")
end

#get(*args, &block) ⇒ Object

Send a GET to the API, handling the response.


31
32
33
# File 'lib/audiosocket/client.rb', line 31

def get *args, &block
  handle @conn.get *args, &block
end

#handle(res) ⇒ Object

Handle and transform Faraday’s response. ‘404` responses return `nil`. Responses from `200` to `299` and `422` parse the body as JSON.


39
40
41
42
43
44
45
46
47
48
# File 'lib/audiosocket/client.rb', line 39

def handle res
  case res.status
  when 200..299, 422 then JSON.parse res.body
  when 401, 403      then raise Audiosocket::Unauthorized
  when 404           then nil

  else
    raise "Unexpected response (#{res.status}) from the API:\n#{res.body}"
  end
end

#post(*args, &block) ⇒ Object

Send a POST to the API, handling the response.


52
53
54
# File 'lib/audiosocket/client.rb', line 52

def post *args, &block
  handle @conn.post *args, &block
end

#put(*args) ⇒ Object

Send a PUT to the API, handling the response.


58
59
60
# File 'lib/audiosocket/client.rb', line 58

def put *args
  handle @conn.put *args
end

#to_sObject


62
63
64
# File 'lib/audiosocket/client.rb', line 62

def to_s
  "#<Audiosocket::Client #{url}>"
end

#tokenizeObject

Create a temporary token for the client’s current token/uid credentials.


69
70
71
# File 'lib/audiosocket/client.rb', line 69

def tokenize
  post("token")["token"]
end