Class: SccRuby::Api

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

Class Method Summary collapse

Class Method Details

.build_url(config_server_url, app_name, app_env) ⇒ Object



50
51
52
# File 'lib/scc_ruby.rb', line 50

def self.build_url(config_server_url, app_name, app_env)
  "#{config_server_url}/#{app_name}/#{app_env}"
end

.fetch(config_server_url, app_name, app_env = 'default', basic_auth_username = '', basic_auth_password = '') ⇒ Object



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

def self.fetch(config_server_url, app_name, app_env = 'default', basic_auth_username = '', basic_auth_password = '')
  uri = URI(build_url(config_server_url, app_name, app_env))
  req = Net::HTTP::Get.new(uri)
  req.basic_auth(basic_auth_username, basic_auth_password) unless basic_auth_username.empty? && basic_auth_password.empty?
  res = Net::HTTP.start(uri.hostname, uri.port) do |http|
    http.request(req)
  end

  if res.code != '200'
    raise "Fail to fetch from spring cloud config server, http code #{res.code}, message #{res.message}"
  end

  json = JSON.parse(res.body)
  h = json['propertySources'].inject(:merge!)['source']

  # try to fix yaml array
  arr_keys = []
  h.keys.each do |k|
    sp = k.split(/\[\d+/)
    arr_keys << sp[0] if (sp.size > 1) && (sp[1] == ']')
  end

  arr_keys.each do |k|
    h[k] = []
  end

  h.each do |k, v|
    next if v.is_a?(Array)

    arr_keys.each do |ak|
      if k.split(/\[\d+/)[0] == ak
        h[ak] << v
        h.delete(k)
      end
    end
  end
  # h.each do |k, v|
  #   h[k] = v.to_s if v.is_a?(Integer)
  #   h[k] = v.map(&:to_s) if v.is_a?(Array)
  # end
  h
end