Class: CiviCrm::Client

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

Class Method Summary collapse

Class Method Details

.execute(opts) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/civicrm/client.rb', line 56

def execute(opts)
  RestClient::Request.execute(opts)
rescue RuntimeError => e
  case e.http_code.to_i
  when 400
    raise CiviCrm::Errors::BadRequest, e.http_body
  when 401
    raise CiviCrm::Errors::Unauthorized, e.http_body
  when 403
    raise CiviCrm::Errors::Forbidden, e.http_body
  when 404
    raise CiviCrm::Errors::NotFound, e.http_body
  when 500
    raise CiviCrm::Errors::InternalError, e.http_body
  else
    raise e
  end
end

.request(method, params = {}) ⇒ Object

Returns parsed class inherited from CiviCrm::Resource

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/civicrm/client.rb', line 6

def request(method, params = {})
  unless CiviCrm.site_key
    raise CiviCrm::Errors::Unauthorized,
          "Please specify CiviCrm.site_key"
  end

  headers = {
    :user_agent => "CiviCrm RubyClient/#{CiviCrm::VERSION}"
  }

  opts = {
    :method => :post,
    :timeout => 80,
    :headers => headers
  }

  params = params.dup

  entity = params.delete("entity")
  raise ArgumentError, "params must include entity" unless entity

  action = params.delete("action")
  raise ArgumentError, "params must include action" unless action

  method = { entity: entity, action: action }.to_query

  opts[:payload] = { json: JSON.dump(params) }
  opts[:url] = CiviCrm.api_url(method)

  response = nil

  CiviCrm.time(params['entity'], params['action']) do
    response = execute(opts)
  end

  puts(JSON.dump(opts)) if ENV["DEBUG_CIVICRM_REQUEST"]
  puts(response) if ENV["DEBUG_CIVICRM_RESPONSE"]

  body, code = response.body, response.code

  parsed_response = JSON.parse(body)

  if parsed_response["is_error"] == 1
    raise Error, parsed_response["error_message"]
  end

  values = parsed_response.fetch("values")
  values.is_a?(Hash) ? values.values : values
end