active_call-zoho_crm 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5692f8ba47b601d8c6781d92154ae4f2b229923bfdb34c5b1537eef054558bc3
4
+ data.tar.gz: 95346571658eddc07819ad96a8b8d2bda19942dcd8d20d23fc6efc4283ff0a24
5
+ SHA512:
6
+ metadata.gz: 5f2d97143511747fec70a48323a0590cd633592b38e379be100c8a12666d31ff20e83c0d6975be5cbe97be265c3792ab931debaa431fe2b46b8e653eab32533e
7
+ data.tar.gz: da622d9adc9047203d77e8c76340ddb3c800f898097d93562b0d381593b7641361d7120dd2c4b88fb8b154d2c74039c37cf2fc615ffcc573c7b33bfca59e24d7
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,82 @@
1
+ plugins:
2
+ - rubocop-performance
3
+ - rubocop-rake
4
+ - rubocop-rspec
5
+
6
+ AllCops:
7
+ TargetRubyVersion: 3.1
8
+ NewCops: enable
9
+ Exclude:
10
+ - zoho_crm.gemspec
11
+ - bin/*
12
+ - 'vendor/**/*'
13
+ - 'gem/**/*'
14
+
15
+ Layout/ArgumentAlignment:
16
+ EnforcedStyle: with_fixed_indentation
17
+
18
+ Layout/HashAlignment:
19
+ EnforcedHashRocketStyle: table
20
+ EnforcedColonStyle: table
21
+
22
+ Layout/LineLength:
23
+ AllowedPatterns:
24
+ - initialize
25
+ - '#'
26
+
27
+ Lint/MissingSuper:
28
+ Enabled: false
29
+
30
+ Metrics/AbcSize:
31
+ Enabled: false
32
+
33
+ Metrics/BlockLength:
34
+ Exclude:
35
+ - spec/*/**.rb
36
+
37
+ Metrics/ClassLength:
38
+ Enabled: false
39
+
40
+ Metrics/CyclomaticComplexity:
41
+ Exclude:
42
+ - lib/zoho_crm/concerns/enumerable.rb
43
+
44
+ Metrics/MethodLength:
45
+ Enabled: false
46
+
47
+ Metrics/ParameterLists:
48
+ Enabled: false
49
+
50
+ Metrics/PerceivedComplexity:
51
+ Exclude:
52
+ - lib/zoho_crm/concerns/enumerable.rb
53
+
54
+ Naming/FileName:
55
+ Exclude:
56
+ - lib/active_call-zoho_crm.rb
57
+
58
+ Naming/MemoizedInstanceVariableName:
59
+ EnforcedStyleForLeadingUnderscores: required
60
+
61
+ RSpec/ExampleLength:
62
+ Enabled: false
63
+
64
+ RSpec/MultipleExpectations:
65
+ Enabled: false
66
+
67
+ Style/ClassAndModuleChildren:
68
+ EnforcedStyle: compact
69
+ Exclude:
70
+ - lib/zoho_crm.rb
71
+
72
+ Style/Documentation:
73
+ Enabled: false
74
+
75
+ Style/StringLiterals:
76
+ EnforcedStyle: single_quotes
77
+
78
+ Style/StringLiteralsInInterpolation:
79
+ EnforcedStyle: single_quotes
80
+
81
+ Style/SymbolArray:
82
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-04-02
4
+
5
+ - Initial release
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Kobus Joubert
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,355 @@
1
+ # Active Call - Zoho CRM
2
+
3
+ Zoho CRM exposes the [Zoho CRM API](https://www.zoho.com/crm/developer/docs/api) endpoints through service objects.
4
+
5
+ - [Installation](#installation)
6
+ - [Configuration](#configuration)
7
+ - [Usage](#usage)
8
+ - [Using call](#using-call)
9
+ - [Using call!](#using-call!)
10
+ - [When to use call or call!](#using-call-or-call!)
11
+ - [Using lists](#using-lists)
12
+ - [Service Objects](#service-objects)
13
+ - [Development](#development)
14
+ - [Contributing](#contributing)
15
+ - [License](#license)
16
+
17
+ ## Installation
18
+
19
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
20
+
21
+ Install the gem and add to the application's Gemfile by executing:
22
+
23
+ ```bash
24
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
25
+ ```
26
+
27
+ If bundler is not being used to manage dependencies, install the gem by executing:
28
+
29
+ ```bash
30
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
31
+ ```
32
+
33
+ ## Configuration
34
+
35
+ Create a new **Self Client** client type from the [Zoho Developer Console](https://api-console.zoho.com) to retrieve your **Client ID** and **Client Secret**.
36
+
37
+ Choose what you need from the list of [Zoho Scopes](https://www.zoho.com/crm/developer/docs/api/v7/scopes.html) like `ZohoCRM.modules.ALL` to generate your **Grant Token**.
38
+
39
+ Get your **Refresh Token** by calling `ZohoCrm::GrantToken::GetService.call(grant_token: '', client_id: '', client_secret: '').refresh_token`
40
+
41
+ Configure your API credentials.
42
+
43
+ In a Rails application, the standard practice is to place this code in a file named `zoho_crm.rb` within the `config/initializers` directory.
44
+
45
+ ```ruby
46
+ require 'active_call-zoho_crm'
47
+
48
+ ZohoCrm::BaseService.configure do |config|
49
+ config.client_id = ''
50
+ config.client_secret = ''
51
+ config.refresh_token = ''
52
+
53
+ # Optional configuration.
54
+ config.cache = Rails.cache # Default: ActiveSupport::Cache::MemoryStore.new
55
+ config.logger = Rails.logger # Default: Logger.new($stdout)
56
+ config.logger_level = :debug # Default: :info
57
+ config.log_headers = true # Default: false
58
+ config.log_bodies = true # Default: false
59
+ end
60
+ ```
61
+
62
+ ## Usage
63
+
64
+ ### <a name='using-call'></a>Using `call`
65
+
66
+ Each service object returned will undergo validation before the `call` method is invoked to access API endpoints.
67
+
68
+ After **successful** validation.
69
+
70
+ ```ruby
71
+ service.success? # => true
72
+ service.errors # => #<ActiveModel::Errors []>
73
+ ```
74
+
75
+ After **failed** validation.
76
+
77
+ ```ruby
78
+ service.success? # => false
79
+ service.errors # => #<ActiveModel::Errors [#<ActiveModel::Error attribute=id, type=blank, options={}>]>
80
+ service.errors.full_messages # => ["Id can't be blank"]
81
+ ```
82
+
83
+ After a **successful** `call` invocation, the `response` attribute will contain a `Faraday::Response` object.
84
+
85
+ ```ruby
86
+ service.success? # => true
87
+ service.response # => #<Faraday::Response ...>
88
+ service.response.success? # => true
89
+ service.response.status # => 200
90
+ service.response.body # => {"data"=> [{"Email"=>"eric.cartman@example.com", ...}]}
91
+ ```
92
+
93
+ At this point you will also have a `facade` object which will hold all the attributes for the specific resource.
94
+
95
+ ```ruby
96
+ service.facade # => #<ZohoCrm::Record::Facade @attributes={"Email"=>"eric.cartman@example.com", ...} ...>
97
+ service.facade.attributes # => {"Email"=>"eric.cartman@example.com", ...}
98
+ ```
99
+
100
+ For convenience, facade attributes can be accessed directly on the service object.
101
+
102
+ ```ruby
103
+ service.attributes # => {"Email"=>"eric.cartman@example.com", ...}
104
+ ```
105
+
106
+ After a **failed** `call` invocation, the `response` attribute will still contain a `Faraday::Response` object.
107
+
108
+ ```ruby
109
+ service.success? # => false
110
+ service.errors # => #<ActiveModel::Errors [#<ActiveModel::Error attribute=base, type=bad_request, options={}>]>
111
+ service.errors.full_messages # => ["Bad Request"]
112
+ service.response # => #<Faraday::Response ...>
113
+ service.response.success? # => false
114
+ service.response.status # => 400
115
+ service.response.body # => {"data"=>[{"code"=>"INVALID_DATA", "details"=>{"api_name"=>"id", "json_path"=>"$.data[0].id"}, "message"=>"the id given seems to be invalid", "status"=>"error"}]}
116
+ ```
117
+
118
+ ### <a name='using-call!'></a>Using `call!`
119
+
120
+ Each service object returned will undergo validation before the `call!` method is invoked to access API endpoints.
121
+
122
+ After **successful** validation.
123
+
124
+ ```ruby
125
+ service.success? # => true
126
+ ```
127
+
128
+ After **failed** validation, a `ZohoCrm::ValidationError` exception will be raised with an `errors` attribute which
129
+ will contain an `ActiveModel::Errors` object.
130
+
131
+ ```ruby
132
+ rescue ZohoCrm::ValidationError => exception
133
+ exception.message # => ''
134
+ exception.errors # => #<ActiveModel::Errors [#<ActiveModel::Error attribute=id, type=blank, options={}>]>
135
+ exception.errors.full_messages # => ["Id can't be blank"]
136
+ ```
137
+
138
+ After a **successful** `call!` invocation, the `response` attribute will contain a `Faraday::Response` object.
139
+
140
+ ```ruby
141
+ service.success? # => true
142
+ service.response # => #<Faraday::Response ...>
143
+ service.response.success? # => true
144
+ service.response.status # => 200
145
+ service.response.body # => {"data"=> [{"Email"=>"eric.cartman@example.com", ...}]}
146
+ ```
147
+
148
+ At this point you will also have a `facade` object which will hold all the attributes for the specific resource.
149
+
150
+ ```ruby
151
+ service.facade # => #<ZohoCrm::Record::Facade @attributes={"Email"=>"eric.cartman@example.com", ...} ...>
152
+ service.facade.attributes # => {"Email"=>"eric.cartman@example.com", ...}
153
+ ```
154
+
155
+ For convenience, facade attributes can be accessed directly on the service object.
156
+
157
+ ```ruby
158
+ service.attributes # => {"Email"=>"eric.cartman@example.com", ...}
159
+ ```
160
+
161
+ After a **failed** `call!` invocation, a `ZohoCrm::RequestError` will be raised with a `response` attribute which will contain a `Faraday::Response` object.
162
+
163
+ ```ruby
164
+ rescue ZohoCrm::RequestError => exception
165
+ exception.message # => 'Bad Request'
166
+ exception.errors # => #<ActiveModel::Errors [#<ActiveModel::Error attribute=base, type=bad_request, options={}>]>
167
+ exception.errors.full_messages # => ["Bad Request"]
168
+ exception.response # => #<Faraday::Response ...>
169
+ exception.response.status # => 400
170
+ exception.response.body # => {"data"=>[{"code"=>"INVALID_DATA", "details"=>{"api_name"=>"id", "json_path"=>"$.data[0].id"}, "message"=>"the id given seems to be invalid", "status"=>"error"}]}
171
+ ```
172
+
173
+ ### <a name='using-call-or-call!'></a>When to use `call` or `call!`
174
+
175
+ An example of where to use `call` would be in a **controller** doing an inline synchronous request.
176
+
177
+ ```ruby
178
+ class SomeController < ApplicationController
179
+ def update
180
+ @service = ZohoCrm::Record::UpdateService.call(**params)
181
+
182
+ if @service.success?
183
+ redirect_to [@service], notice: 'Success', status: :see_other
184
+ else
185
+ flash.now[:alert] = @service.errors.full_messages.to_sentence
186
+ render :edit, status: :unprocessable_entity
187
+ end
188
+ end
189
+ end
190
+ ```
191
+
192
+ An example of where to use `call!` would be in a **job** doing an asynchronous request.
193
+
194
+ You can use the exceptions to determine which retry strategy to use and which to discard.
195
+
196
+ ```ruby
197
+ class SomeJob < ApplicationJob
198
+ discard_on ZohoCrm::NotFoundError
199
+
200
+ retry_on ZohoCrm::RequestTimeoutError, wait: 5.minutes, attempts: :unlimited
201
+ retry_on ZohoCrm::TooManyRequestsError, wait: :polynomially_longer, attempts: 10
202
+
203
+ def perform
204
+ ZohoCrm::Record::UpdateService.call!(**params)
205
+ end
206
+ end
207
+ ```
208
+
209
+ ### Using lists
210
+
211
+ If you don't provide the `per_page` argument, multiple API requests will be made untill all records have been returned. You could be rate limited, so use wisely.
212
+
213
+ ## Service Objects
214
+
215
+ <details open>
216
+ <summary>Records</summary>
217
+
218
+ ### Records
219
+
220
+ ##### Supported modules
221
+
222
+ `Leads`, `Accounts`, `Contacts`, `Deals`, `Campaigns`, `Tasks`, `Cases`, `Events`, `Calls`, `Solutions`, `Products`, `Vendors`, `Price Books`, `Quotes`, `Sales Orders`, `Purchase Orders`, `Invoices`, `Custom`, `Appointments`, `Appointments Rescheduled History`, `Services` and `Activities`
223
+
224
+ ##### Custom modules
225
+
226
+ For custom modules, use their respective API names in the request URL. You can obtain the API name from **Setup -> Developer Hub -> APIs & SDKs -> API Names**. You can also use the respective custom module's `api_name` key in the [Modules API's](https://www.zoho.com/crm/developer/docs/api/v7/modules-api.html) response to get the API name of the custom module.
227
+
228
+ #### List records
229
+
230
+ ```ruby
231
+ ZohoCrm::Record::ListService.call(module_name: 'Contacts', fields: 'Email,Last_Name', page: 1, per_page: 10).each do |facade|
232
+ facade.attributes
233
+ end
234
+ ```
235
+
236
+ Sort by column.
237
+
238
+ ```ruby
239
+ ZohoCrm::Record::ListService.call(module_name: 'Contacts', fields: 'Email,Last_Name', sort_by: 'Modified_Time', sort_order: 'asc').map { _1 }
240
+ ```
241
+
242
+ Columns to sort by are `id`, `Created_Time` and `Modified_Time`.
243
+
244
+ #### Search records
245
+
246
+ ```ruby
247
+ ZohoCrm::Record::SearchService.call(module_name: 'Contacts', email: 'eric.cartman@example.com', page: 1, per_page: 10).each do |facade|
248
+ facade.attributes
249
+ end
250
+ ```
251
+
252
+ Sort by column.
253
+
254
+ ```ruby
255
+ ZohoCrm::Record::SearchService.call(module_name: 'Contacts', email: 'eric.cartman@example.com', sort_by: 'Modified_Time', sort_order: 'asc').map { _1 }
256
+ ```
257
+
258
+ Columns to sort by are `id`, `Created_Time` and `Modified_Time`.
259
+
260
+ Search by email.
261
+
262
+ ```ruby
263
+ ZohoCrm::Record::SearchService.call(module_name: 'Contacts', email: 'eric.cartman@example.com').map { _1 }
264
+ ```
265
+
266
+ Search by phone.
267
+
268
+ ```ruby
269
+ ZohoCrm::Record::SearchService.call(module_name: 'Contacts', phone: '0123456789').map { _1 }
270
+ ```
271
+
272
+ Search by criteria.
273
+
274
+ ```ruby
275
+ ZohoCrm::Record::SearchService.call(module_name: 'Contacts', criteria: 'Created_Time:between:2025-01-01T06:00:00+00:00,2025-01-30T06:00:00+00:00').map { _1 }
276
+ ```
277
+
278
+ Search by word.
279
+
280
+ ```ruby
281
+ ZohoCrm::Record::SearchService.call(module_name: 'Contacts', word: 'eric').map { _1 }
282
+ ```
283
+
284
+ #### Get a record
285
+
286
+ ```ruby
287
+ service = ZohoCrm::Record::GetService.call(module_name: 'Contacts', id: '')
288
+ service.id
289
+ service.attributes
290
+ service.attributes['Email']
291
+ service.attributes['Record_Status__s']
292
+ service.attributes['Owner']['name']
293
+ ...
294
+ ```
295
+
296
+ #### Create a record
297
+
298
+ ```ruby
299
+ service = ZohoCrm::Record::CreateService.call(
300
+ module_name: 'Contacts',
301
+ data: {
302
+ 'Email' => 'eric.cartman@example.com',
303
+ 'First_Name' => 'Eric',
304
+ 'Last_Name' => 'Cartman'
305
+ }
306
+ )
307
+ ```
308
+
309
+ #### Update a record
310
+
311
+ ```ruby
312
+ service = ZohoCrm::Record::UpdateService.call(
313
+ module_name: 'Contacts',
314
+ data: {
315
+ 'id' => '',
316
+ 'First_Name' => 'Eric Theodore'
317
+ }
318
+ )
319
+ ```
320
+
321
+ #### Upsert a record
322
+
323
+ ```ruby
324
+ service = ZohoCrm::Record::UpsertService.call(
325
+ module_name: 'Contacts',
326
+ data: {
327
+ 'Email' => 'eric.cartman@example.com',
328
+ 'First_Name' => 'Eric',
329
+ 'Last_Name' => 'Cartman Theodore 2nd'
330
+ },
331
+ duplicate_check_fields: ['Email']
332
+ )
333
+ ```
334
+
335
+ #### Delete a record
336
+
337
+ ```ruby
338
+ service = ZohoCrm::Record::DeleteService.call(module_name: 'Contacts', id: '')
339
+ ```
340
+
341
+ </details>
342
+
343
+ ## Development
344
+
345
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
346
+
347
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
348
+
349
+ ## Contributing
350
+
351
+ Bug reports and pull requests are welcome on GitHub at https://github.com/kobusjoubert/zoho_crm.
352
+
353
+ ## License
354
+
355
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'zoho_crm'
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ class ZohoCrm::AccessToken::Facade
4
+ attr_reader :access_token, :api_domain, :expires_in, :scope, :token_type
5
+
6
+ def initialize(hash)
7
+ @access_token = hash['access_token']
8
+ @api_domain = hash['api_domain']
9
+ @expires_in = hash['expires_in']
10
+ @scope = hash['scope']
11
+ @token_type = hash['token_type']
12
+ end
13
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ class ZohoCrm::AccessToken::GetService < ZohoCrm::BaseService
4
+ skip_callback :call, :before, :set_access_token
5
+
6
+ after_call :set_facade
7
+
8
+ delegate_missing_to :@facade
9
+
10
+ # Get access token.
11
+ #
12
+ # ==== Examples
13
+ #
14
+ # service = ZohoCrm::AccessToken::GetService.call
15
+ # service.access_token # => '1000.xxxx.yyyy'
16
+ # service.expires_in # => 3600
17
+ #
18
+ # POST /oauth/v2/token
19
+ def call
20
+ connection.post('oauth/v2/token', params.to_param)
21
+ end
22
+
23
+ private
24
+
25
+ def connection
26
+ @_connection ||= Faraday.new do |conn|
27
+ conn.url_prefix = 'https://accounts.zoho.com'
28
+ conn.request :retry
29
+ conn.response :json
30
+ conn.response :logger, logger, **logger_options do |logger|
31
+ logger.filter(/(refresh_token|client_id|client_secret)=([^&]+)/i, '\1=[FILTERED]')
32
+ logger.filter(/"access_token":"([^"]+)"/i, '"access_token":"[FILTERED]"')
33
+ end
34
+ conn.adapter Faraday.default_adapter
35
+ end
36
+ end
37
+
38
+ def params
39
+ {
40
+ client_id: client_id,
41
+ client_secret: client_secret,
42
+ refresh_token: refresh_token,
43
+ grant_type: 'refresh_token'
44
+ }
45
+ end
46
+
47
+ def unauthorized?
48
+ response.status == 200 && response.body.key?('error')
49
+ end
50
+
51
+ def set_facade
52
+ @facade = ZohoCrm::AccessToken::Facade.new(response.body)
53
+ end
54
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ class ZohoCrm::BaseService < ActiveCall::Base
4
+ include ActiveCall::Api
5
+
6
+ self.abstract_class = true
7
+
8
+ CACHE_KEY = { access_token: 'zoho_sign/base_service/access_token' }.freeze
9
+
10
+ config_accessor :base_url, default: 'https://www.zohoapis.com/crm/v7', instance_writer: false
11
+ config_accessor :cache, default: ActiveSupport::Cache::MemoryStore.new, instance_writer: false
12
+ config_accessor :logger, default: Logger.new($stdout), instance_writer: false
13
+ config_accessor :log_level, default: :info, instance_writer: false
14
+ config_accessor :log_headers, default: false, instance_writer: false
15
+ config_accessor :log_bodies, default: false, instance_writer: false
16
+ config_accessor :client_id, :client_secret, :refresh_token, instance_writer: false
17
+
18
+ attr_reader :access_token, :facade
19
+
20
+ before_call :set_access_token
21
+
22
+ validate on: :request do
23
+ next if is_a?(ZohoCrm::AccessToken::GetService) || is_a?(ZohoCrm::GrantToken::GetService)
24
+
25
+ errors.merge!(access_token_service.errors) if access_token.nil? && !access_token_service.success?
26
+ end
27
+
28
+ class << self
29
+ def exception_mapping
30
+ {
31
+ validation_error: ZohoCrm::ValidationError,
32
+ request_error: ZohoCrm::RequestError,
33
+ client_error: ZohoCrm::ClientError,
34
+ server_error: ZohoCrm::ServerError,
35
+ bad_request: ZohoCrm::BadRequestError,
36
+ unauthorized: ZohoCrm::UnauthorizedError,
37
+ forbidden: ZohoCrm::ForbiddenError,
38
+ not_found: ZohoCrm::NotFoundError,
39
+ method_not_allowed: ZohoCrm::MethodNotAllowedError,
40
+ not_acceptable: ZohoCrm::NotAcceptableError,
41
+ proxy_authentication_required: ZohoCrm::ProxyAuthenticationRequiredError,
42
+ request_timeout: ZohoCrm::RequestTimeoutError,
43
+ conflict: ZohoCrm::ConflictError,
44
+ gone: ZohoCrm::GoneError,
45
+ payload_too_large: ZohoCrm::PayloadTooLargeError,
46
+ unsupported_media_type: ZohoCrm::UnsupportedMediaTypeError,
47
+ unprocessable_entity: ZohoCrm::UnprocessableEntityError,
48
+ too_many_requests: ZohoCrm::TooManyRequestsError,
49
+ internal_server_error: ZohoCrm::InternalServerError,
50
+ not_implemented: ZohoCrm::NotImplementedError,
51
+ bad_gateway: ZohoCrm::BadGatewayError,
52
+ service_unavailable: ZohoCrm::ServiceUnavailableError,
53
+ gateway_timeout: ZohoCrm::GatewayTimeoutError
54
+ }.freeze
55
+ end
56
+ end
57
+
58
+ private
59
+
60
+ def connection
61
+ @_connection ||= Faraday.new do |conn|
62
+ conn.url_prefix = base_url
63
+ # conn.headers['If-Modified-Since'] = '2019-07-25T15:26:49+05:30'
64
+ conn.request :authorization, 'Zoho-oauthtoken', access_token
65
+ conn.request :json
66
+ conn.request :retry
67
+ conn.response :json
68
+ conn.response :logger, logger, **logger_options do |logger|
69
+ logger.filter(/(Authorization:).*"(.+)."/i, '\1 [FILTERED]')
70
+ end
71
+ conn.adapter Faraday.default_adapter
72
+ end
73
+ end
74
+
75
+ def logger_options
76
+ {
77
+ headers: log_headers,
78
+ log_level: log_level,
79
+ bodies: log_bodies,
80
+ formatter: Faraday::Logging::ColorFormatter, prefix: { request: 'ZohoCrm', response: 'ZohoCrm' }
81
+ }
82
+ end
83
+
84
+ def set_access_token
85
+ @access_token = cache.read(CACHE_KEY[:access_token])
86
+ return if @access_token.present?
87
+ return unless access_token_service.success?
88
+
89
+ @access_token = cache.fetch(CACHE_KEY[:access_token], expires_in: [access_token_service.expires_in - 10, 0].max) do
90
+ access_token_service.facade.access_token
91
+ end
92
+ end
93
+
94
+ def access_token_service
95
+ @_access_token_service ||= ZohoCrm::AccessToken::GetService.call
96
+ end
97
+
98
+ def too_many_requests?
99
+ return false unless response.status == 400 && response.body.key?('error_description')
100
+
101
+ response.body['error_description'].include?('too many requests')
102
+ end
103
+ end