Class: SimpleWorker::Api::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_worker/api.rb

Overview

Subclass must define:

host: endpoint url for service

Direct Known Subclasses

Service

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, token, options = {}) ⇒ Client

Returns a new instance of Client.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/simple_worker/api.rb', line 48

def initialize(host, token, options={})
  @config = options[:config]
  @scheme = options[:scheme] || @config.scheme || "https"
  @host = options[:host] || @config.host || host
  @port = options[:port] || @config.port || 443
  @token = options[:token] || @config.token || token
  @version = options[:version]
  #@logger = options[:logger]

  @base_url = "#{@scheme}://#{@host}:#{@port}/#{@version}"

  @uber_client = Uber::Client.new

end

Instance Attribute Details

#configObject

Returns the value of attribute config.



46
47
48
# File 'lib/simple_worker/api.rb', line 46

def config
  @config
end

#hostObject

Returns the value of attribute host.



46
47
48
# File 'lib/simple_worker/api.rb', line 46

def host
  @host
end

#portObject

Returns the value of attribute port.



46
47
48
# File 'lib/simple_worker/api.rb', line 46

def port
  @port
end

#schemeObject

Returns the value of attribute scheme.



46
47
48
# File 'lib/simple_worker/api.rb', line 46

def scheme
  @scheme
end

#tokenObject

Returns the value of attribute token.



46
47
48
# File 'lib/simple_worker/api.rb', line 46

def token
  @token
end

#versionObject

Returns the value of attribute version.



46
47
48
# File 'lib/simple_worker/api.rb', line 46

def version
  @version
end

Instance Method Details

#add_params(command_path, hash) ⇒ Object



202
203
204
205
# File 'lib/simple_worker/api.rb', line 202

def add_params(command_path, hash)
  extra_params = {'oauth' => token}
  hash.merge!(extra_params)
end

#append_params(host, params) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
# File 'lib/simple_worker/api.rb', line 207

def append_params(host, params)
  host += "?"
  i = 0
  params.each_pair do |k, v|
    #puts "k=#{k} v=#{v}"
    host += "&" if i > 0
    host += k + "=" + (v.is_a?(String) ? CGI.escape(v) : v.to_s)
    i +=1
  end
  return host
end

#base_urlObject



64
65
66
# File 'lib/simple_worker/api.rb', line 64

def base_url
  @base_url
end

#check_response(response, options = {}) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/simple_worker/api.rb', line 100

def check_response(response, options={})
  # response.code    # http status code
  #response.time    # time in seconds the request took
  #response.headers # the http headers
  #response.headers_hash # http headers put into a hash
  #response.body    # the response body
  status = response.code
  body = response.body
  # todo: check content-type == application/json before parsing
  logger.debug "response code=" + status.to_s
  logger.debug "response body=" + body.inspect
  res = nil
  unless options[:parse] == false
    res = JSON.parse(body)
  end
  if status < 400

  else
    raise SimpleWorker::RequestError.new((res ? "#{status}: #{res["msg"]}" : "#{status} Error! parse=false so no msg"), :status=>status)
  end
  res || body
end

#common_req_hashObject



80
81
82
83
84
85
86
# File 'lib/simple_worker/api.rb', line 80

def common_req_hash
  {
      :headers=>{"Content-Type" => 'application/json',
                 "Authorization"=>"OAuth #{@token}",
                 "User-Agent"=>"SimpleWorker Ruby Client"}
  }
end

#delete(method, params = {}, options = {}) ⇒ Object



193
194
195
196
197
198
199
200
# File 'lib/simple_worker/api.rb', line 193

def delete(method, params={}, options={})
  begin
    # todo: replace with uber_client
    parse_response RestClient.delete(append_params(url_full(method), add_params(method, params))), options
  rescue RestClient::Exception => ex
    process_ex(ex)
  end
end

#get(method, params = {}, options = {}) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/simple_worker/api.rb', line 123

def get(method, params={}, options={})
  full_url = url_full(method)
  #all_params = add_params(method, params)
  #url_plus_params = append_params(full_url, all_params)
  logger.debug 'get url=' + full_url
  req_hash = common_req_hash
  req_hash[:params] = params
  response = @uber_client.get(full_url, req_hash) # could let typhoeus add params, using :params=>x
  #response = @http_sess.request(:get, url_plus_params,
  #                              {},
  #                              {})
  check_response(response, options)
  body = response.body
  parse_response(body, options)

end

#headersObject



219
220
221
222
# File 'lib/simple_worker/api.rb', line 219

def headers
  user_agent = "SimpleWorker Ruby Client"
  headers = {'User-Agent' => user_agent}
end

#parse_response(response, options = {}) ⇒ Object



224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/simple_worker/api.rb', line 224

def parse_response(response, options={})
  #puts 'PARSE RESPONSE: ' + response.to_s
  unless options[:parse] == false
    begin
      return JSON.parse(response.to_s)
    rescue => ex
      puts 'parse_response: response that caused error = ' + response.to_s
      raise ex
    end
  else
    response
  end
end

#post(method, params = {}, options = {}) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/simple_worker/api.rb', line 155

def post(method, params={}, options={})
  logger.debug "params = " + params.inspect
  logger.debug "options = " + options.inspect
  logger.debug "params.payload = " + params[:payload].inspect
  logger.debug "token = "+ token.inspect
  begin
    url = url_full(method)
    logger.debug 'post url=' + url
    json = add_params(method, params).to_json
    logger.debug 'body=' + json
    req_hash = common_req_hash
    req_hash[:body] = json
    response = @uber_client.post(url, req_hash)
    #response = @http_sess.post(url, json, {"Content-Type" => 'application/json'})
    check_response(response)
    logger.debug 'response: ' + response.inspect
    body = response.body
    parse_response(body, options)
  rescue SimpleWorker::RequestError => ex
    # let it throw, came from check_response
    raise ex
  rescue RestClient::Exception => ex
    logger.warn("Exception in post! #{ex.message}")
    logger.warn(ex.backtrace.join("\n"))
    process_ex(ex)
  end
end

#post_file(method, file, params = {}, options = {}) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/simple_worker/api.rb', line 140

def post_file(method, file, params={}, options={})
  begin
    data = add_params(method, params).to_json
    url = url_full(method)
    logger.debug "post_file url = " + url
    logger.debug "data = " + data
    logger.debug "params = " + params.inspect
    logger.debug "options = " + options.inspect
    # todo: replace with uber_client
    parse_response(RestClient.post(append_params(url, add_params(method, params)), {:data => data, :file => file}, :content_type => 'application/json'), options)
  rescue RestClient::Exception => ex
    process_ex(ex)
  end
end

#process_ex(ex) ⇒ Object



88
89
90
91
92
93
94
95
96
97
# File 'lib/simple_worker/api.rb', line 88

def process_ex(ex)
  logger.error "EX #{ex.class.name}: #{ex.message}"
  body = ex.http_body
  logger.debug 'EX http_code: ' + ex.http_code.to_s
  logger.debug 'EX BODY=' + body.to_s
  decoded_ex = JSON.parse(body)
  exception = Exception.new(ex.message + ": " + decoded_ex["msg"])
  exception.set_backtrace(decoded_ex["backtrace"].split(",")) if decoded_ex["backtrace"]
  raise exception
end

#put(method, body, options = {}) ⇒ Object



184
185
186
187
188
189
190
191
# File 'lib/simple_worker/api.rb', line 184

def put(method, body, options={})
  begin
    # todo: replace with uber_client
    parse_response RestClient.put(url_full(method), add_params(method, body).to_json, headers), options
  rescue RestClient::Exception => ex
    process_ex(ex)
  end
end

#url(command_path) ⇒ Object



68
69
70
71
# File 'lib/simple_worker/api.rb', line 68

def url(command_path)
  # @logger.debug "url: " + url.to_s
  "/#{command_path}"
end

#url_full(command_path) ⇒ Object



73
74
75
76
77
# File 'lib/simple_worker/api.rb', line 73

def url_full(command_path)
  url = "#{base_url}/#{command_path}"
  # @logger.debug "url: " + url.to_s
  url
end