Class: Cxf::Client

Inherits:
Object
  • Object
show all
Extended by:
ActiveSupport::Concern
Includes:
CxfHelper
Defined in:
lib/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from CxfHelper

#correct_json, #data_transform, #get_query_results

Constructor Details

#initialize(host, api_key, scope = nil, contact_token_id = nil, visit_id = nil, debug = false, timeouts = {}) ⇒ Client

Returns a new instance of Client.



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
# File 'lib/client.rb', line 18

def initialize(
  host,
  api_key,
  scope = nil,
  contact_token_id = nil,
  visit_id = nil,
  debug = false,
  timeouts = {}
)

  @host = host
  @api_key = api_key
  @contact_token_id = contact_token_id
  @visit_id = visit_id
  @debug = debug
  @user_agent = nil
  @response_cookies = nil

  config = read_config_file('sdk') || {}

  @default_http_timeout = timeouts.fetch(:default, config.fetch('default_http_timeout', 30))
  @get_http_timeout = timeouts.fetch(:get, config.fetch('get_http_timeout', @default_http_timeout))
  @post_http_timeout = timeouts.fetch(:post, config.fetch('post_http_timeout', @default_http_timeout))
  @put_http_timeout = timeouts.fetch(:put, config.fetch('put_http_timeout', @default_http_timeout))
  @delete_http_timeout = timeouts.fetch(:delete, config.fetch('delete_http_timeout', @default_http_timeout))

  self.set_scope(scope)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/client.rb', line 171

def method_missing(name, *args, &block)
  name.to_s.include?('__') ? separator = '__' : separator = '_'
  # split the name to identify their elements
  name_splitted = name.to_s.split(separator)
  # count the elements
  name_len = name_splitted.size
  # the action always be the first element
  action = name_splitted.first
  valid_actions = %w[
    get
    create
    post
    update
    put
    delete
    destroy
    verify_response_status
  ]

  raise 'NoActionError' unless valid_actions.include?(action)

  # the object always be the last element
  object = separator == '__' ? name_splitted.last.gsub('_', '-') : name_splitted.last
  # get intermediate url elements
  route_array = []
  (name_len - 1).times do |n|
    next if n === 0 or n === name_len - 1

    n = name_splitted[n]
    self.replacements.each do |object|
      n = n.gsub(object[:old_value], object[:new_value])
    end
    route_array.push n
  end
  route = route_array.join('/')

  slug = nil
  response = nil
  uri = Addressable::URI.new

  if action == 'get'
    if args.first.class == Hash
      uri.query_values = args.first
    elsif args.first.class == String or Integer
      slug = args.first
      uri.query_values = args[1]
    end

    url = self.get_url(route, object, uri, slug)
    response = self.send("#{@scope}_#{action}", url, nil, compatibility_options)
  elsif action == 'post' or action == 'create'
    if args[1].class == Hash
      uri.query_values = args[1]
    end

    url = self.get_url(route, object, uri, slug)
    action = 'post'
    data = args[0]
    response = self.send("#{@scope}_#{action}", url, { data: data }, compatibility_options)
  elsif action == 'put' or action == 'update'
    if args.first.class == String or Integer
      slug = args.first
      uri.query_values = args[2]
    end

    url = self.get_url(route, object, uri, slug)
    action = 'put'
    data = args[1]
    response = self.send("#{@scope}_#{action}", "#{url}", { data: data }, compatibility_options)
  end

  verify_response_status(response, config['sdk']['ignore_http_errors'])

  response ? JSON.parse(response.body) : nil
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



15
16
17
# File 'lib/client.rb', line 15

def api_key
  @api_key
end

#base_urlObject (readonly)

Returns the value of attribute base_url.



15
16
17
# File 'lib/client.rb', line 15

def base_url
  @base_url
end

#contact_token_idObject

Returns the value of attribute contact_token_id.



16
17
18
# File 'lib/client.rb', line 16

def contact_token_id
  @contact_token_id
end

#hostObject (readonly)

Returns the value of attribute host.



15
16
17
# File 'lib/client.rb', line 15

def host
  @host
end

#modeObject (readonly)

Returns the value of attribute mode.



15
16
17
# File 'lib/client.rb', line 15

def mode
  @mode
end

#response_cookiesObject

Returns the value of attribute response_cookies.



16
17
18
# File 'lib/client.rb', line 16

def response_cookies
  @response_cookies
end

#scopeObject (readonly)

Returns the value of attribute scope.



15
16
17
# File 'lib/client.rb', line 15

def scope
  @scope
end

#user_agentObject

Returns the value of attribute user_agent.



16
17
18
# File 'lib/client.rb', line 16

def user_agent
  @user_agent
end

Instance Method Details

#contact_get(url, headers = nil, compatibility_options) ⇒ Object

Start contact context



297
298
299
300
301
# File 'lib/client.rb', line 297

def contact_get(url, headers = nil, compatibility_options)
  h = set_headers(compatibility_options, headers)

  self.http_get(url, h)
end

#contact_post(url, data, compatibility_options) ⇒ Object



303
304
305
306
307
# File 'lib/client.rb', line 303

def contact_post(url, data, compatibility_options)
  headers = set_headers(compatibility_options)

  self.http_post(url, headers, data)
end

#contact_put(url, data, compatibility_options) ⇒ Object



309
310
311
312
313
# File 'lib/client.rb', line 309

def contact_put(url, data, compatibility_options)
  headers = set_headers(compatibility_options)

  self.http_put(url, headers, data)
end

#get_tokensObject



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/client.rb', line 348

def get_tokens
  if @scope === 'user'
    return {
      access_token: @response_cookies.fetch('cxf_user_access_token', ''),
      refresh_token: @response_cookies.fetch('cxf_user_refresh_token', '')
    }
  elsif @scope === 'contact'
    return {
      access_token: @response_cookies.fetch('cxf_contact_access_token', ''),
      refresh_token: @response_cookies.fetch('cxf_contact_refresh_token', '')
    }
  end

  return nil
end

#get_url(route, object, uri, slug = nil) ⇒ Object



247
248
249
250
251
252
253
# File 'lib/client.rb', line 247

def get_url(route, object, uri, slug = nil)
  if slug
    "#{@host}#{@base_url}/#{route}/#{object}/#{slug}#{uri}"
  else
    "#{@host}#{@base_url}/#{route}/#{object}#{uri}"
  end
end

#http_delete(url, headers = nil, data = nil) ⇒ Object

Simple HTTP DELETE



292
293
294
# File 'lib/client.rb', line 292

def http_delete(url, headers = nil, data = nil)
  HTTParty.delete(url, headers: headers, body: data, timeout: @delete_http_timeout)
end

#http_get(url, headers = nil) ⇒ Object

HTTP CLIENTS ###### Simple HTTP GET



277
278
279
# File 'lib/client.rb', line 277

def http_get(url, headers = nil)
  HTTParty.get(url, headers: headers, timeout: @get_http_timeout)
end

#http_post(url, headers = nil, data = nil) ⇒ Object

Simple HTTP POST



282
283
284
# File 'lib/client.rb', line 282

def http_post(url, headers = nil, data = nil)
  HTTParty.post(url, headers: headers, body: data, timeout: @post_http_timeout)
end

#http_put(url, headers = nil, data = nil) ⇒ Object

Simple HTTP PUT



287
288
289
# File 'lib/client.rb', line 287

def http_put(url, headers = nil, data = nil)
  HTTParty.put(url, headers: headers, body: data, timeout: @put_http_timeout)
end

#is_singular?(str) ⇒ Boolean

Returns:

  • (Boolean)


458
459
460
# File 'lib/client.rb', line 458

def is_singular?(str)
  str.pluralize != str && str.singularize == str
end

#parse_set_cookies(header_string) ⇒ Object

def split_cookie_header(header_string)

header_string.scan(/(?:^|, )([^=;]+=[^;]+(?:;[^,]*)*)/).flatten

end



488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/client.rb', line 488

def parse_set_cookies(header_string)
  return {} unless header_string.is_a?(String)

  cookies = []
  buffer = ''
  inside_cookie = false

  # Split cookies
  header_string.split(',').each do |part|
    if part.strip =~ /^[^=]+=/ && !inside_cookie
      buffer = part
      inside_cookie = true
    elsif part.strip.downcase.start_with?('expires=')
      buffer += ',' + part
    elsif inside_cookie && part.strip.include?('=')
      buffer += ',' + part
      cookies << buffer.strip
      buffer = ''
      inside_cookie = false
    else
      buffer += ',' + part
    end
  end
  cookies << buffer.strip unless buffer.empty?

  parsed = {}

  cookies.each do |cookie_string|
    parts = cookie_string.split(/;\s*/)
    name_value = parts.shift
    name, value = name_value.split('=', 2)
    next unless name && value

    cookie = { 'name' => name, 'value' => value }

    parts.each do |part|
      if part.downcase.start_with?('expires=')
        # Rebuild expires
        cookie['expires'] = part[8..].strip
      elsif part.include?('=')
        k, v = part.split('=', 2)
        cookie[k.strip.downcase] = v.strip
      else
        cookie[part.strip.downcase] = true
      end
    end

    parsed[name] = cookie
  end

  parsed
end

#public_get(url, headers = nil, compatibility_options) ⇒ Object

End User Context



336
337
338
# File 'lib/client.rb', line 336

def public_get(url, headers = nil, compatibility_options)
  self.http_get(url, set_headers(compatibility_options, headers))
end

#public_post(url, headers = nil, data, compatibility_options) ⇒ Object



340
341
342
# File 'lib/client.rb', line 340

def public_post(url, headers = nil, data, compatibility_options)
  self.http_post(url, set_headers(compatibility_options, headers), data)
end

#public_put(url, headers = nil, data, compatibility_options) ⇒ Object



344
345
346
# File 'lib/client.rb', line 344

def public_put(url, headers = nil, data, compatibility_options)
  self.http_put(url, set_headers(compatibility_options, headers), data)
end

#raw(action, url, options = nil, data = nil, base_url = nil, compatibility_options = {}, only_tracking = false, disable_data_transform = false) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/client.rb', line 47

def raw(action, url, options = nil, data = nil, base_url = nil, compatibility_options = {}, only_tracking = false, disable_data_transform = false)
  compatibility_options = {} if compatibility_options.nil?

  data = data_transform(data) unless disable_data_transform or action == 'get'

  base_url = @base_url unless base_url
  uri = ''

  # get the first method called in this instance, example: get_deal(1)
  method_called = caller[0][/`.*'/][1..-2]

  # this can't be "!url.last.to_i" because we have methods like .me
  if is_singular?(method_called) && %w[// nil].include?(url)
    error_class = Errors::DynamicError.new(
      self,
      'Unprocessed entity',
      "Id must be a valid integer number, given URL: #{url}",
      'undefined_id',
      nil
    )

    raise error_class if @debug

    raise error_class.error
  end

  if options&.class == Hash
    need_encoding = %w[jfilters afilters rfilters]
    found_options_with_encoding = options.keys.select { |key| need_encoding.include?(key.to_s.downcase) and options[key]&.class == Hash }

    found_options_with_encoding.each do |key|
      options[key] = Base64.encode64(options[key].to_json)
    end

    uri = Addressable::URI.new
    uri.query_values = options
  end

  full_url = "#{@host}#{base_url}#{url}#{uri}"
  response = nil

  template = ERB.new File.new("#{Rails.root}/cxf_config.yml.erb").read
  config = YAML.safe_load template.result(binding)
  result_from_cache = false

  if action === 'get'
    url_need_cache = false

    if config['redis_cache']['use_cache']
      config['redis_cache']['groups'].each do |group|
        group['urls'].each do |url|
          if full_url.match url
            time = group['time']
            url_need_cache = true
            @redis_server = Redis.new(
              host: config['redis_cache']['redis_host'],
              port: config.dig('redis_cache', 'redis_port') || 6379,
              db: config.dig('redis_cache', 'redis_db') || 1
            )
            response = @redis_server.get(full_url)

            if response
              result_from_cache = true

              if only_tracking
                # headers = { 'Only-Tracking' => 'true' }
                # when is already in redis notify to California to register the object usage
                # cali_response = self.send("#{@scope}_#{action}", full_url, headers, compatibility_options)
              end
            else
              response = self.send("#{@scope}_#{action}", full_url, nil, compatibility_options)
              @redis_server.setex(full_url, time, response)
            end
            break
          end
        end

        break if url_need_cache
      end
    end

    unless url_need_cache
      response = self.send("#{@scope}_#{action}", full_url, nil, compatibility_options)
      set_cookies(response.headers)
    end

  elsif action === 'create' or action === 'post'
    action = 'post'
    response = self.send("#{@scope}_#{action}", full_url, data, compatibility_options)
    set_cookies(response.headers)
  elsif action === 'put' or action === 'patch' or action === 'update'
    action = 'put'
    response = self.send("#{@scope}_#{action}", full_url, data, compatibility_options)
    set_cookies(response.headers)
  elsif action === 'delete' or action === 'destroy'
    action = 'delete'
    response = self.send("#{@scope}_#{action}", full_url, data, compatibility_options)
    set_cookies(response.headers)
  end

  response = verify_response_status(response, config['sdk']['ignore_http_errors'])

  begin
    if @debug
      response_from = if result_from_cache
                        'REDIS'
                      else
                        'CALI'
                      end

      puts "Method: #{action} \nURL: #{url} \nOptions: #{options&.to_json} \nOnly tracking: #{only_tracking} \nResponse from: #{response_from}"
      puts "Data: #{data.to_json}" if data
    end

    if result_from_cache
      return JSON.parse(response)
    else
      return JSON.parse(response&.body)
    end
  rescue
    return response
  end
end

#read_config_file(config_key = nil) ⇒ Object



450
451
452
453
454
455
456
# File 'lib/client.rb', line 450

def read_config_file(config_key = nil)
  template = ERB.new File.new("#{Rails.root}/cxf_config.yml.erb").read
  config = YAML.safe_load template.result(binding)
  config_key ? config[config_key] : config
rescue StandardError
  nil
end

#replacementsObject



255
256
257
258
259
260
261
# File 'lib/client.rb', line 255

def replacements
  [
    { old_value: '_', new_value: '-' },
    { old_value: 'people', new_value: 'customer-data' },
    { old_value: 'store', new_value: 'ecommerce' }
  ]
end

#set_cookies(headers) ⇒ Object



462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/client.rb', line 462

def set_cookies(headers)
  string_headers = headers['set-cookie'];
  # use parse_cookies_header of rack
  @response_cookies = parse_set_cookies(headers['set-cookie'])

  # parsed_cookies.each_value do |cookie|
  #   Rack::Utils.set_cookie_header!(
  #     response.headers,
  #     cookie['name'],
  #     {
  #       value: cookie['value'],
  #       expires: cookie['expires'] ? Time.parse(cookie['expires']) : nil,
  #       path: cookie['path'] || '/',
  #       domain: '', # especificar si necesitas uno
  #       secure: cookie['secure'] || false,
  #       httponly: cookie['httponly'] || false,
  #       same_site: (cookie['samesite'] || 'Lax').capitalize
  #     }
  #   )
  # end
end

#set_headers(compatibility_options, headers = nil) ⇒ Object



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/client.rb', line 364

def set_headers(compatibility_options, headers = nil)
  headers = {} if headers.nil?
  h = {
    'Accept' => 'application/json',
    'ApiKey' => @api_key,
  }
  h['Content-Type'] = 'application/json' unless compatibility_options['no_content_type']
  h['ContactToken'] = @contact_token_id if @contact_token_id
  h['Visit-Id'] = @visit_id if @visit_id
  h['User-Agent'] = @user_agent if @user_agent

  tokens = get_tokens
  if tokens
    h['Access-Token'] = tokens[:access_token] if tokens[:access_token]
    h['Refresh-Token'] = tokens[:refresh_token] if tokens[:refresh_token]
  end

  if headers
    headers.each do |k, v|
      h[k] = v
    end
  end

  h
end

#set_scope(scope) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
# File 'lib/client.rb', line 263

def set_scope(scope)
  @scope = scope
  if scope === 'public' or scope === 'contact'
    @base_url = '/api/v1'
  elsif scope === 'user'
    @base_url = '/api/user/v1'
  else
    @scope = 'public'
    @base_url = '/api/v1'
  end
end

#timeoutObject

Timeouts methods



423
424
425
426
427
428
429
430
431
# File 'lib/client.rb', line 423

def timeout
  {
    default: @default_http_timeout,
    get: @get_http_timeout,
    post: @post_http_timeout,
    put: @put_http_timeout,
    delete: @delete_http_timeout
  }
end

#timeout=(t) ⇒ Object



433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/client.rb', line 433

def timeout=(t)
  if t.kind_of? Hash
    t = t.with_indifferent_access
    @default_http_timeout = t[:default] if t[:default]
    @get_http_timeout = t[:get] if t[:get]
    @post_http_timeout = t[:post] if t[:post]
    @put_http_timeout = t[:put] if t[:put]
    @delete_http_timeout = t[:delete] if t[:delete]
  elsif t.kind_of? Integer
    @default_http_timeout = t
    @get_http_timeout = t
    @post_http_timeout = t
    @put_http_timeout = t
    @delete_http_timeout = t
  end
end

#user_delete(url, data, compatibility_options) ⇒ Object



330
331
332
# File 'lib/client.rb', line 330

def user_delete(url, data, compatibility_options)
  self.http_delete(url, set_headers(compatibility_options), data)
end

#user_get(url, headers = nil, compatibility_options) ⇒ Object

Start User context



316
317
318
319
320
# File 'lib/client.rb', line 316

def user_get(url, headers = nil, compatibility_options)
  h = set_headers(compatibility_options, headers)

  self.http_get(url, h)
end

#user_post(url, data, compatibility_options) ⇒ Object



322
323
324
# File 'lib/client.rb', line 322

def user_post(url, data, compatibility_options)
  self.http_post(url, set_headers(compatibility_options), data)
end

#user_put(url, data, compatibility_options) ⇒ Object



326
327
328
# File 'lib/client.rb', line 326

def user_put(url, data, compatibility_options)
  self.http_put(url, set_headers(compatibility_options), data)
end

#verify_response_status(response, ignore_http_errors) ⇒ Object



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/client.rb', line 390

def verify_response_status(response, ignore_http_errors)
  # Verify if the response is cached
  unless response.kind_of? String
    # Raise an error if response code is not 2xx
    http_status = response&.response&.code&.to_i || 500
    is_success = (http_status >= 200 and http_status < 300)

    if !is_success and !ignore_http_errors
      title = "Request failed with status #{http_status}"
      detail = response&.parsed_response["message"] || response&.response&.message || 'Unknown error'

      if @debug
        puts "Error detected: #{http_status}"
        error_class = Errors::DynamicError.new(self, title, detail, http_status, response&.parsed_response)
        raise error_class
      end

      response = JSON.generate(
        {
          'error' => {
            'title' => title,
            'status' => http_status
          },
          'message' => detail
        }
      )
    end
  end
  response
end