Class: BusinessCentral::Object::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/business_central/object/request.rb

Class Method Summary collapse

Class Method Details

.convert(request = {}) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/business_central/object/request.rb', line 25

def convert(request = {})
  result = {}
  request.each do |key, value|
    result[key.to_s.to_camel_case] = value if key.is_a? Symbol
    result[key.to_s] = value if key.is_a? String
  end

  result.to_json
end

.delete(client, url, etag) ⇒ Object



21
22
23
# File 'lib/business_central/object/request.rb', line 21

def delete(client, url, etag)
  request(:delete, client, url, etag: etag)
end

.get(client, url) ⇒ Object



9
10
11
# File 'lib/business_central/object/request.rb', line 9

def get(client, url)
  request(:get, client, url)
end

.patch(client, url, etag, params) ⇒ Object



17
18
19
# File 'lib/business_central/object/request.rb', line 17

def patch(client, url, etag, params)
  request(:patch, client, url, etag: etag, params: params)
end

.post(client, url, params) ⇒ Object



13
14
15
# File 'lib/business_central/object/request.rb', line 13

def post(client, url, params)
  request(:post, client, url, params: params)
end

.request(method, client, url, etag: '', params: {}) ⇒ Object Also known as: call



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/business_central/object/request.rb', line 35

def request(method, client, url, etag: '', params: {})
  send do
    uri = URI(url)
    https = Net::HTTP.new(uri.host, uri.port)
    https.use_ssl = true
    https.set_debug_output($stdout) if client.debug
    request = Object.const_get("Net::HTTP::#{method.to_s.capitalize}").new(uri)
    request['If-Match'] = etag if !etag.blank?
    request['Accept'] = 'application/json'
    if block_given?
      yield(request)
    else
      request['Content-Type'] = 'application/json'
      request.body = convert(params) if %i[post patch].include?(method)
    end

    if client.access_token
      request['Authorization'] = "Bearer #{client.access_token.token}"
    else
      request.basic_auth(client.username, client.password)
    end
    https.request(request)
  end
end