Module: Zendesk2::Request

Included in:
CreateBrand, CreateCategory, CreateForum, CreateGroup, CreateHelpCenterArticle, CreateHelpCenterCategory, CreateHelpCenterPost, CreateHelpCenterSection, CreateHelpCenterSubscription, CreateHelpCenterTopic, CreateHelpCenterTranslation, CreateMembership, CreateOrganization, CreateTicket, CreateTicketField, CreateTicketForm, CreateTopic, CreateTopicComment, CreateUser, CreateUserField, CreateUserIdentity, CreateView, DestroyBrand, DestroyCategory, DestroyForum, DestroyGroup, DestroyHelpCenterArticle, DestroyHelpCenterCategory, DestroyHelpCenterPost, DestroyHelpCenterSection, DestroyHelpCenterSubscription, DestroyHelpCenterTopic, DestroyHelpCenterTranslation, DestroyMembership, DestroyOrganization, DestroyTicket, DestroyTicketField, DestroyTicketForm, DestroyTopic, DestroyTopicComment, DestroyUser, DestroyUserField, DestroyUserIdentity, DestroyView, GetAssignableGroups, GetBrand, GetBrands, GetCategories, GetCategory, GetCcdTickets, GetCurrentUser, GetForum, GetForums, GetGroup, GetGroups, GetHelpCenterAccessPolicy, GetHelpCenterArticle, GetHelpCenterArticles, GetHelpCenterCategories, GetHelpCenterCategoriesArticles, GetHelpCenterCategoriesSections, GetHelpCenterCategory, GetHelpCenterPost, GetHelpCenterPosts, GetHelpCenterSection, GetHelpCenterSections, GetHelpCenterSectionsArticles, GetHelpCenterSubscription, GetHelpCenterSubscriptions, GetHelpCenterTopic, GetHelpCenterTopics, GetHelpCenterTranslation, GetHelpCenterTranslations, GetMembership, GetMemberships, GetOrganization, GetOrganizationByExternalId, GetOrganizationMemberships, GetOrganizationTickets, GetOrganizationUsers, GetOrganizations, GetRequestedTickets, GetTicket, GetTicketAudit, GetTicketAudits, GetTicketComments, GetTicketField, GetTicketFields, GetTicketForm, GetTicketForms, GetTicketMetric, GetTicketMetrics, GetTickets, GetTopic, GetTopicComment, GetTopicComments, GetTopics, GetUser, GetUserField, GetUserFields, GetUserIdentities, GetUserIdentity, GetUserMemberships, GetUserOrganizations, GetUsers, GetUsersHelpCenterSubscriptions, GetView, GetViewTickets, GetViews, MarkMembershipDefault, MarkUserIdentityPrimary, Search, SearchHelpCenterArticles, SearchOrganization, SearchUser, UpdateBrand, UpdateCategory, UpdateForum, UpdateGroup, UpdateHelpCenterAccessPolicy, UpdateHelpCenterArticle, UpdateHelpCenterCategory, UpdateHelpCenterPost, UpdateHelpCenterSection, UpdateHelpCenterSubscription, UpdateHelpCenterTopic, UpdateHelpCenterTranslation, UpdateOrganization, UpdateTicket, UpdateTicketField, UpdateTicketForm, UpdateTopic, UpdateUser, UpdateUserField, UpdateUserIdentity, UpdateView
Defined in:
lib/zendesk2/request.rb

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#paramsObject (readonly)

Returns the value of attribute params.



53
54
55
# File 'lib/zendesk2/request.rb', line 53

def params
  @params
end

Class Method Details

.cistern_includedObject



4
# File 'lib/zendesk2/request.rb', line 4

alias cistern_included included

.included(receiver) ⇒ Object



6
7
8
9
10
# File 'lib/zendesk2/request.rb', line 6

def included(receiver)
  receiver.extend(ClassMethods)
  cistern_included(receiver)
  super
end

Instance Method Details

#call(*args) ⇒ Object



55
56
57
58
59
60
# File 'lib/zendesk2/request.rb', line 55

def call(*args)
  params = args.last.is_a?(Hash) ? args.pop : {}
  @params = Cistern::Hash.stringify_keys(params)

  dispatch
end

#dataObject



110
111
112
# File 'lib/zendesk2/request.rb', line 110

def data
  cistern.data
end

#delete!(collection, identity, options = {}) ⇒ Object



164
165
166
167
# File 'lib/zendesk2/request.rb', line 164

def delete!(collection, identity, options = {})
  cistern.data[collection].delete(identity.to_i) ||
    error!(options[:error] || :not_found, options)
end

#error!(type, options = {}) ⇒ Object



169
170
171
172
173
174
175
176
177
178
# File 'lib/zendesk2/request.rb', line 169

def error!(type, options = {})
  status, body = self.class.error_map[type]
  body['details'] = options[:details] if options[:details]

  response(
    path: request_path,
    status: status,
    body: body,
  )
end

#find!(collection, identity, options = {}) ⇒ Object



159
160
161
162
# File 'lib/zendesk2/request.rb', line 159

def find!(collection, identity, options = {})
  resource = cistern.data[collection][identity.to_i]
  resource || error!(options[:error] || :not_found, options)
end

#html_url_for(path) ⇒ Object



114
115
116
# File 'lib/zendesk2/request.rb', line 114

def html_url_for(path)
  File.join(cistern.url, path.to_s)
end

#mock_response(body, options = {}) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
# File 'lib/zendesk2/request.rb', line 147

def mock_response(body, options = {})
  response(
    method: self.class.request_method,
    path: options[:path] || request_path,
    request_body: request_body,
    response_body: body,
    headers: options[:headers] || {},
    status: options[:status]  || 200,
    params: options[:params]  || request_params,
  )
end

#page(collection, options = {}) ⇒ Object



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

def page(collection, options = {})
  url_params = options[:params] || params
  page_params = page_params!(params)

  page_size  = (page_params.delete('per_page') || 50).to_i
  page_index = (page_params.delete('page') || 1).to_i
  root       = options.fetch(:root) { !collection.is_a?(Array) && collection.to_s }
  path       = options[:path] || request_path

  offset     = (page_index - 1) * page_size

  resources   = collection.is_a?(Array) ? collection : cistern.data[collection.to_sym].values
  count       = resources.size
  total_pages = (count / page_size) + 1

  next_page = if page_index < total_pages
                url_for(path, query: { 'page' => page_index + 1, 'per_page' => page_size }.merge(url_params))
              end
  previous_page = if page_index > 1
                    url_for(path, query: { 'page' => page_index - 1, 'per_page' => page_size }.merge(url_params))
                  end

  resource_page = resources.slice(offset, page_size)

  body = {
    root            => resource_page,
    'count'         => count,
    'next_page'     => next_page,
    'previous_page' => previous_page,
  }

  response(
    body: body,
    path: path,
  )
end

#page_params!(options) ⇒ Object



62
63
64
65
66
67
68
69
70
71
# File 'lib/zendesk2/request.rb', line 62

def page_params!(options)
  url = options.delete('url')

  page_params = if url
                  Faraday::NestedParamsEncoder.decode(URI.parse(url).query)
                else
                  Cistern::Hash.stringify_keys(options)
                end
  Cistern::Hash.slice(page_params, 'per_page', 'page', 'query')
end

#page_params?Boolean

Returns:

  • (Boolean)


73
74
75
# File 'lib/zendesk2/request.rb', line 73

def page_params?
  self.class.page_params?
end

#pluralize(word) ⇒ Object



104
105
106
107
108
# File 'lib/zendesk2/request.rb', line 104

def pluralize(word)
  pluralized = word.dup
  [[/y$/, 'ies'], [/$/, 's']].find { |regex, replace| pluralized.gsub!(regex, replace) if pluralized.match(regex) }
  pluralized
end

#real(params = {}) ⇒ Object



127
128
129
130
131
132
133
# File 'lib/zendesk2/request.rb', line 127

def real(params = {})
  cistern.request(method: self.class.request_method,
                  path: request_path,
                  body: request_body,
                  url: params['url'],
                  params: request_params,)
end

#real_request(params = {}) ⇒ Object



135
136
137
138
139
140
141
# File 'lib/zendesk2/request.rb', line 135

def real_request(params = {})
  request({
    method: self.class.request_method,
    path: request_path(params),
    body: request_body(params),
  }.merge(cistern.hash.slice(params, :method, :path, :body, :headers),),)
end

#request_bodyObject



95
96
97
98
99
100
101
102
# File 'lib/zendesk2/request.rb', line 95

def request_body
  case (generator = self.class.request_body)
  when Proc then
    generator.call(self)
  when NilClass then nil
  else raise("Invalid request body generator: #{generator.inspect}")
  end
end

#request_paramsObject



77
78
79
80
81
82
83
84
85
# File 'lib/zendesk2/request.rb', line 77

def request_params
  page_params = (page_params!(params) if page_params?)

  if self.class.request_params
    self.class.request_params.call(self)
  else
    page_params
  end
end

#request_pathObject



87
88
89
90
91
92
93
# File 'lib/zendesk2/request.rb', line 87

def request_path
  case (generator = self.class.request_path)
  when Proc then
    generator.call(self)
  else raise ArgumentError, "Couldn't generate request_path from #{generator.inspect}"
  end
end

#resources(collection, options = {}) ⇒ Object



180
181
182
183
184
185
186
187
188
# File 'lib/zendesk2/request.rb', line 180

def resources(collection, options = {})
  page = collection.is_a?(Array) ? collection : cistern.data[collection.to_sym].values
  root = options.fetch(:root) { !collection.is_a?(Array) && collection.to_s }

  mock_response(
    root    => page,
    'count' => page.size,
  )
end

#response(options = {}) ⇒ Object

Note:

id values are validate for format / type

{

"error": {
  "title": "Invalid attribute",
  "message": "You passed an invalid value for the id attribute. must be an integer"
}

} @request_body is special because it’s need for spec assertions but Faraday::Env replaces the request body with the response body after the request and the reference is lost



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/zendesk2/request.rb', line 241

def response(options = {})
  body                 = options[:response_body] || options[:body]
  method               = options[:method]        || :get
  params               = options[:params]
  cistern.last_request = options[:request_body]
  status               = options[:status] || 200

  path = options[:path]
  url  = options[:url] || url_for(path, query: params)

  request_headers  = { 'Accept'       => 'application/json' }
  response_headers = { 'Content-Type' => 'application/json; charset=utf-8' }

  # request phase
  # * :method - :get, :post, ...
  # * :url    - URI for the current request; also contains GET parameters
  # * :body   - POST parameters for :post/:put requests
  # * :request_headers

  # response phase
  # * :status - HTTP response status code, such as 200
  # * :body   - the response body
  # * :response_headers
  env = Faraday::Env.from(
    method: method,
    url: URI.parse(url),
    body: body,
    request_headers: request_headers,
    response_headers: response_headers,
    status: status,
  )

  Faraday::Response::RaiseError.new.on_complete(env) ||
    Faraday::Response.new(env)
rescue Faraday::Error::ClientError => e
  raise Zendesk2::Error, e
end

#timestampObject



143
144
145
# File 'lib/zendesk2/request.rb', line 143

def timestamp
  Time.now.iso8601
end

#url_for(path, options = {}) ⇒ Object



118
119
120
121
122
123
124
125
# File 'lib/zendesk2/request.rb', line 118

def url_for(path, options = {})
  URI.parse(
    File.join(cistern.url, '/api/v2', path.to_s),
  ).tap do |uri|
    query = options[:query]
    query && (uri.query = Faraday::NestedParamsEncoder.encode(query))
  end.to_s
end