Module: WhenIWork::Request

Included in:
Client
Defined in:
lib/wheniwork/request.rb

Instance Method Summary collapse

Instance Method Details

#auth_paramsObject



62
63
64
65
66
67
68
# File 'lib/wheniwork/request.rb', line 62

def auth_params
  {
    username: WhenIWork.configuration.username,
    password: WhenIWork.configuration.password,
    key:      WhenIWork.configuration.api_key
  }
end

#cache_enabledObject



78
79
80
# File 'lib/wheniwork/request.rb', line 78

def cache_enabled
  WhenIWork.configuration.cache_enabled
end

#cache_key_for(uri, params) ⇒ Object



26
27
28
29
# File 'lib/wheniwork/request.rb', line 26

def cache_key_for(uri, params)
  params[:uri] = uri
  ::Marshal.dump(params)
end

#cache_storeObject



74
75
76
# File 'lib/wheniwork/request.rb', line 74

def cache_store
  WhenIWork.configuration.cache_store
end

#connectionObject



35
36
37
38
39
40
41
42
# File 'lib/wheniwork/request.rb', line 35

def connection
  @connection ||= Faraday.new(:url => endpoint) do |faraday|
    faraday.request  :url_encoded

    faraday.response :json, :content_type => /\bjson$/
    faraday.adapter  Faraday.default_adapter
  end
end

#default_optionsObject



31
32
33
# File 'lib/wheniwork/request.rb', line 31

def default_options
  { expires_in: WhenIWork.configuration.expires_in }
end

#default_request_paramsObject



44
45
46
# File 'lib/wheniwork/request.rb', line 44

def default_request_params
  { "W-Token" => token }
end

#endpointObject



48
49
50
# File 'lib/wheniwork/request.rb', line 48

def endpoint
  WhenIWork.configuration.endpoint
end

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



4
5
6
# File 'lib/wheniwork/request.rb', line 4

def get(path, params={}, options={})
  request :get, path, default_request_params.merge(params), options
end

#loginObject



70
71
72
# File 'lib/wheniwork/request.rb', line 70

def 
  connection.post('login', auth_params.to_json).body
end

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



8
9
10
# File 'lib/wheniwork/request.rb', line 8

def post(path, params={}, options={})
  request :post, path, default_request_params.merge(params), options
end

#request(method, path, params, cache_options) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/wheniwork/request.rb', line 12

def request(method, path, params, cache_options)
  if cache_enabled
    key = cache_options.delete(:key) || cache_key_for(path, params)
    options = default_options.merge(cache_options)

    cache_store.fetch(key, options) do
      connection.send(method, path, params).body
    end
  else
    connection.send(method, path, params).body
  end      
  
end

#tokenObject



52
53
54
55
56
57
58
59
60
# File 'lib/wheniwork/request.rb', line 52

def token
  if cache_enabled
    cache_store.fetch('wheniwork_token', default_options) do
      ['token']
    end
  else
    ['token']
  end
end