Class: Refocus::Http

Inherits:
Object
  • Object
show all
Defined in:
lib/refocus/http.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, token:, content_type: "application/json") ⇒ Http

Returns a new instance of Http.



8
9
10
11
12
# File 'lib/refocus/http.rb', line 8

def initialize(url:, token:, content_type: "application/json")
  @url = url
  @token = token
  @content_type = content_type
end

Instance Attribute Details

#content_typeObject (readonly)

Returns the value of attribute content_type.



6
7
8
# File 'lib/refocus/http.rb', line 6

def content_type
  @content_type
end

#tokenObject (readonly)

Returns the value of attribute token.



6
7
8
# File 'lib/refocus/http.rb', line 6

def token
  @token
end

#urlObject (readonly)

Returns the value of attribute url.



6
7
8
# File 'lib/refocus/http.rb', line 6

def url
  @url
end

Instance Method Details

#connection(path) ⇒ Object



52
53
54
# File 'lib/refocus/http.rb', line 52

def connection(path)
  Excon.new("#{url}/#{path}")
end

#convert(body) ⇒ Object



48
49
50
# File 'lib/refocus/http.rb', line 48

def convert(body)
  content_type == "application/json" ? body.to_json : body
end

#delete(path) ⇒ Object



30
31
32
# File 'lib/refocus/http.rb', line 30

def delete(path)
  handle { connection(path).delete(headers: headers, expects: 200) }
end

#get(path) ⇒ Object



18
19
20
# File 'lib/refocus/http.rb', line 18

def get(path)
  handle { connection(path).get(headers: headers, expects: 200) }
end

#handle(&block) ⇒ Object



34
35
36
37
38
39
# File 'lib/refocus/http.rb', line 34

def handle(&block)
  yield
rescue Excon::Error::BadRequest => e
  response = JSON.parse(e.response.body)["errors"].first["message"]
  raise ApiError, JSON.parse(e.response.body)
end

#headersObject



41
42
43
44
45
46
# File 'lib/refocus/http.rb', line 41

def headers
  {
    "Authorization" => token,
    "Content-Type" => content_type
  }
end

#patch(path, body:) ⇒ Object



22
23
24
# File 'lib/refocus/http.rb', line 22

def patch(path, body:)
  handle { connection(path).patch(body: convert(body), headers: headers, expects: 200) }
end

#post(path, body:, expects: 201) ⇒ Object



14
15
16
# File 'lib/refocus/http.rb', line 14

def post(path, body:, expects: 201)
  handle { connection(path).post(body: convert(body), headers: headers, expects: expects) }
end

#put(path, body:) ⇒ Object



26
27
28
# File 'lib/refocus/http.rb', line 26

def put(path, body:)
  handle { connection(path).put(body: convert(body), headers: headers, expects: 201) }
end