Class: Ordrin::APIHelper

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

Instance Method Summary collapse

Constructor Details

#initialize(api_key, servers) ⇒ APIHelper

Returns a new instance of APIHelper.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/ordrin/api_helper.rb', line 10

def initialize(api_key, servers)
  @api_key = api_key
  @urls = {}
  if servers==:production
    @urls[:restaurant] = "https://r.ordr.in"
    @urls[:user] = "https://u.ordr.in"
    @urls[:order] = "https://o.ordr.in"
  elsif servers==:test
    @urls[:restaurant] = "https://r-test.ordr.in"
    @urls[:user] = "https://u-test.ordr.in"
    @urls[:order] = "https://o-test.ordr.in"
  else
    raise ArgumentError.new("servers must be set to :production, :test, or :custom")
  end
  dir = File.dirname(__FILE__)
  @ENDPOINT_INFO = JSON.parse!(File.read(File.join(dir, "schemas.json")))
end

Instance Method Details

#call_api(base_url, method, uri, data = nil, login = nil) ⇒ Object



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
55
56
57
58
59
60
# File 'lib/ordrin/api_helper.rb', line 28

def call_api(base_url, method, uri, data=nil, =nil)
  methods = {"GET" => Net::HTTP::Get,
    "POST" => Net::HTTP::Post,
    "PUT" => Net::HTTP::Put,
    "DELETE" => Net::HTTP::Delete}
  method = methods[method]
  full_url = URI.parse(base_url+uri)
  req = method.new(full_url.request_uri)
  if not data.nil?
    req.body = URI.encode_www_form(data)
  end
  if not @api_key.empty?
    req['X-NAAMA-CLIENT-AUTHENTICATION'] = "id=\"#{@api_key}\", version=\"1\""
  end
  if not .nil?
    hash_code = Digest::SHA256.new.hexdigest("#{[:password]}#{[:email]}#{uri}")
    req['X-NAAMA-AUTHENTICATION'] = "username=\"#{[:email]}\", response=\"#{hash_code}\", version=\"1\""
  end
  http = Net::HTTP.new(full_url.host, full_url.port)
  if full_url.scheme == "https"
    http.use_ssl = true
    http.ca_file = File.join(File.dirname(__FILE__), "cacert.pem")
  end
  res = http.start {|http| http.request(req)}
  #error if not OK response
  result = JSON.parse(res.body)
  if result.is_a? Hash
    if (result.has_key?('_error') and result['_error']!=0) or (result.has_key?('_err') and result['_err']!=0)
      raise res.body
    end
  end
  result
end

#call_endpoint(endpoint_group, endpoint_name, url_params, kwargs) ⇒ Object



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

def call_endpoint(endpoint_group, endpoint_name, url_params, kwargs)
  endpoint_data = @ENDPOINT_INFO[endpoint_group.to_s][endpoint_name]
  value_mutators = {};
  endpoint_data["properties"].each do |name, info|
    if info.has_key?("mutator")
      value_mutators[name] = Mutate.method(info["mutator"].intern)
    else
      value_mutators[name] = Mutate.method(:identity)
    end
  end
  if endpoint_data.has_key?("allOf")
    endpoint_data["allOf"].each do |subschema|
      subschema["oneOf"].each do |option|
        option["properties"].each do |name, info|
          if info.has_key?("mutator")
            value_mutators[name] = Mutate.method(info["mutator"].intern)
          else
            value_mutators[name] = Mutate.method(:identity)
          end
        end
      end
    end
  end
  if not value_mutators.has_key?("email")
    value_mutators["email"] = Mutate.method(:identity)
  end
  JSON::Validator.validate!(endpoint_data, kwargs)
  arg_dict = {}
  url_params.each do |name|
    arg_dict[name.intern] = URI.encode(value_mutators[name].call(kwargs[name]))
  end

  data = {}
  kwargs.each do |name, value|
    if value_mutators.has_key?(name)
      data[name] = value_mutators[name].call(value)
    end
  end
  data.keep_if do |name, value|
    not (url_params.include?(name) or name == "current_password")
  end
  if data.empty?
    data = nil
  end
  tmpl = endpoint_data["meta"]["uri"].gsub(/\{.+?\}/, '%\0')
  uri = tmpl % arg_dict
   = nil
  if endpoint_data["meta"]["userAuth"]
    if not (kwargs.has_key?("email") and kwargs.has_key?("current_password"))
      raise ArgumentError.new("Authenticated request requires arguments 'email' and 'current_password'")
    end
     = {email: kwargs["email"], password: Mutate.sha256(kwargs["current_password"])}
  end
  call_api(@urls[endpoint_group], endpoint_data["meta"]["method"], uri, data, )
end