first-class-postcodes 0.0.1

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.
@@ -0,0 +1,374 @@
1
+ require 'date'
2
+ require 'json'
3
+ require 'logger'
4
+ require 'tempfile'
5
+ require 'typhoeus'
6
+
7
+ module FCP
8
+ class ApiClient
9
+ # The Configuration object holding settings to be used in the API client.
10
+ attr_accessor :config
11
+
12
+ # Defines the headers to be used in HTTP requests of all API calls by default.
13
+ #
14
+ # @return [Hash]
15
+ attr_accessor :default_headers
16
+
17
+ # Initializes the ApiClient
18
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
19
+ def initialize(config = Configuration.default)
20
+ @config = config
21
+ @user_agent = "FCP/ruby"
22
+ @default_headers = {
23
+ 'Content-Type' => 'application/json',
24
+ 'User-Agent' => @user_agent
25
+ }
26
+ end
27
+
28
+ def self.default
29
+ @@default ||= ApiClient.new
30
+ end
31
+
32
+ # Call an API with given options.
33
+ #
34
+ # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
35
+ # the data deserialized from response body (could be nil), response status code and response headers.
36
+ def call_api(http_method, path, opts = {})
37
+ request = build_request(http_method, path, opts)
38
+ response = request.run
39
+
40
+ if @config.debugging
41
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
42
+ end
43
+
44
+ unless response.success?
45
+ if response.timed_out?
46
+ fail ApiError.new('Connection timed out')
47
+ elsif response.code == 0
48
+ # Errors from libcurl will be made visible here
49
+ fail ApiError.new(:code => 0,
50
+ :message => response.return_message)
51
+ else
52
+ fail ApiError.new(:code => response.code,
53
+ :response_headers => response.headers,
54
+ :response_body => response.body),
55
+ response.status_message
56
+ end
57
+ end
58
+
59
+ if opts[:return_type]
60
+ data = deserialize(response, opts[:return_type])
61
+ else
62
+ data = nil
63
+ end
64
+ return data, response.code, response.headers
65
+ end
66
+
67
+ # Builds the HTTP request
68
+ #
69
+ # @param [String] http_method HTTP method/verb (e.g. POST)
70
+ # @param [String] path URL path (e.g. /account/new)
71
+ # @option opts [Hash] :header_params Header parameters
72
+ # @option opts [Hash] :query_params Query parameters
73
+ # @option opts [Hash] :form_params Query parameters
74
+ # @option opts [Object] :body HTTP body (JSON/XML)
75
+ # @return [Typhoeus::Request] A Typhoeus Request
76
+ def build_request(http_method, path, opts = {})
77
+ url = build_request_url(path)
78
+ http_method = http_method.to_sym.downcase
79
+
80
+ header_params = @default_headers.merge(opts[:header_params] || {})
81
+ query_params = opts[:query_params] || {}
82
+ form_params = opts[:form_params] || {}
83
+
84
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
85
+
86
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
87
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
88
+
89
+ req_opts = {
90
+ :method => http_method,
91
+ :headers => header_params,
92
+ :params => query_params,
93
+ :params_encoding => @config.params_encoding,
94
+ :timeout => @config.timeout,
95
+ :ssl_verifypeer => @config.verify_ssl,
96
+ :ssl_verifyhost => _verify_ssl_host,
97
+ :sslcert => @config.cert_file,
98
+ :sslkey => @config.key_file,
99
+ :verbose => @config.debugging
100
+ }
101
+
102
+ # set custom cert, if provided
103
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
104
+
105
+ if [:post, :patch, :put, :delete].include?(http_method)
106
+ req_body = build_request_body(header_params, form_params, opts[:body])
107
+ req_opts.update :body => req_body
108
+ if @config.debugging
109
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
110
+ end
111
+ end
112
+
113
+ request = Typhoeus::Request.new(url, req_opts)
114
+ download_file(request) if opts[:return_type] == 'File'
115
+ request
116
+ end
117
+
118
+ # Check if the given MIME is a JSON MIME.
119
+ # JSON MIME examples:
120
+ # application/json
121
+ # application/json; charset=UTF8
122
+ # APPLICATION/JSON
123
+ # */*
124
+ # @param [String] mime MIME
125
+ # @return [Boolean] True if the MIME is application/json
126
+ def json_mime?(mime)
127
+ (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
128
+ end
129
+
130
+ # Deserialize the response to the given return type.
131
+ #
132
+ # @param [Response] response HTTP response
133
+ # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
134
+ def deserialize(response, return_type)
135
+ body = response.body
136
+
137
+ # handle file downloading - return the File instance processed in request callbacks
138
+ # note that response body is empty when the file is written in chunks in request on_body callback
139
+ return @tempfile if return_type == 'File'
140
+
141
+ return nil if body.nil? || body.empty?
142
+
143
+ # return response body directly for String return type
144
+ return body if return_type == 'String'
145
+
146
+ # ensuring a default content type
147
+ content_type = response.headers['Content-Type'] || 'application/json'
148
+
149
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
150
+
151
+ begin
152
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
153
+ rescue JSON::ParserError => e
154
+ if %w(String Date DateTime).include?(return_type)
155
+ data = body
156
+ else
157
+ raise e
158
+ end
159
+ end
160
+
161
+ convert_to_type data, return_type
162
+ end
163
+
164
+ # Convert data to the given return type.
165
+ # @param [Object] data Data to be converted
166
+ # @param [String] return_type Return type
167
+ # @return [Mixed] Data in a particular type
168
+ def convert_to_type(data, return_type)
169
+ return nil if data.nil?
170
+ case return_type
171
+ when 'String'
172
+ data.to_s
173
+ when 'Integer'
174
+ data.to_i
175
+ when 'Float'
176
+ data.to_f
177
+ when 'Boolean'
178
+ data == true
179
+ when 'DateTime'
180
+ # parse date time (expecting ISO 8601 format)
181
+ DateTime.parse data
182
+ when 'Date'
183
+ # parse date time (expecting ISO 8601 format)
184
+ Date.parse data
185
+ when 'Object'
186
+ # generic object (usually a Hash), return directly
187
+ data
188
+ when /\AArray<(.+)>\z/
189
+ # e.g. Array<Pet>
190
+ sub_type = $1
191
+ data.map { |item| convert_to_type(item, sub_type) }
192
+ when /\AHash\<String, (.+)\>\z/
193
+ # e.g. Hash<String, Integer>
194
+ sub_type = $1
195
+ {}.tap do |hash|
196
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
197
+ end
198
+ else
199
+ # models, e.g. Pet
200
+ FCP.const_get(return_type).build_from_hash(data)
201
+ end
202
+ end
203
+
204
+ # Save response body into a file in (the defined) temporary folder, using the filename
205
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
206
+ # The response body is written to the file in chunks in order to handle files which
207
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
208
+ # process can use.
209
+ #
210
+ # @see Configuration#temp_folder_path
211
+ def download_file(request)
212
+ tempfile = nil
213
+ encoding = nil
214
+ request.on_headers do |response|
215
+ content_disposition = response.headers['Content-Disposition']
216
+ if content_disposition && content_disposition =~ /filename=/i
217
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
218
+ prefix = sanitize_filename(filename)
219
+ else
220
+ prefix = 'download-'
221
+ end
222
+ prefix = prefix + '-' unless prefix.end_with?('-')
223
+ encoding = response.body.encoding
224
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
225
+ @tempfile = tempfile
226
+ end
227
+ request.on_body do |chunk|
228
+ chunk.force_encoding(encoding)
229
+ tempfile.write(chunk)
230
+ end
231
+ request.on_complete do |response|
232
+ tempfile.close if tempfile
233
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
234
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
235
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
236
+ "explicitly with `tempfile.delete`"
237
+ end
238
+ end
239
+
240
+ # Sanitize filename by removing path.
241
+ # e.g. ../../sun.gif becomes sun.gif
242
+ #
243
+ # @param [String] filename the filename to be sanitized
244
+ # @return [String] the sanitized filename
245
+ def sanitize_filename(filename)
246
+ filename.gsub(/.*[\/\\]/, '')
247
+ end
248
+
249
+ def build_request_url(path)
250
+ # Add leading and trailing slashes to path
251
+ path = "/#{path}".gsub(/\/+/, '/')
252
+ @config.base_url + path
253
+ end
254
+
255
+ # Builds the HTTP request body
256
+ #
257
+ # @param [Hash] header_params Header parameters
258
+ # @param [Hash] form_params Query parameters
259
+ # @param [Object] body HTTP body (JSON/XML)
260
+ # @return [String] HTTP body data in the form of string
261
+ def build_request_body(header_params, form_params, body)
262
+ # http form
263
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
264
+ header_params['Content-Type'] == 'multipart/form-data'
265
+ data = {}
266
+ form_params.each do |key, value|
267
+ case value
268
+ when ::File, ::Array, nil
269
+ # let typhoeus handle File, Array and nil parameters
270
+ data[key] = value
271
+ else
272
+ data[key] = value.to_s
273
+ end
274
+ end
275
+ elsif body
276
+ data = body.is_a?(String) ? body : body.to_json
277
+ else
278
+ data = nil
279
+ end
280
+ data
281
+ end
282
+
283
+ # Update hearder and query params based on authentication settings.
284
+ #
285
+ # @param [Hash] header_params Header parameters
286
+ # @param [Hash] query_params Query parameters
287
+ # @param [String] auth_names Authentication scheme name
288
+ def update_params_for_auth!(header_params, query_params, auth_names)
289
+ Array(auth_names).each do |auth_name|
290
+ auth_setting = @config.auth_settings[auth_name]
291
+ next unless auth_setting
292
+ case auth_setting[:in]
293
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
294
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
295
+ else fail ArgumentError, 'Authentication token must be in `query` of `header`'
296
+ end
297
+ end
298
+ end
299
+
300
+ # Sets user agent in HTTP header
301
+ #
302
+ # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
303
+ def user_agent=(user_agent)
304
+ @user_agent = user_agent
305
+ @default_headers['User-Agent'] = @user_agent
306
+ end
307
+
308
+ # Return Accept header based on an array of accepts provided.
309
+ # @param [Array] accepts array for Accept
310
+ # @return [String] the Accept header (e.g. application/json)
311
+ def select_header_accept(accepts)
312
+ return nil if accepts.nil? || accepts.empty?
313
+ # use JSON when present, otherwise use all of the provided
314
+ json_accept = accepts.find { |s| json_mime?(s) }
315
+ json_accept || accepts.join(',')
316
+ end
317
+
318
+ # Return Content-Type header based on an array of content types provided.
319
+ # @param [Array] content_types array for Content-Type
320
+ # @return [String] the Content-Type header (e.g. application/json)
321
+ def select_header_content_type(content_types)
322
+ # use application/json by default
323
+ return 'application/json' if content_types.nil? || content_types.empty?
324
+ # use JSON when present, otherwise use the first one
325
+ json_content_type = content_types.find { |s| json_mime?(s) }
326
+ json_content_type || content_types.first
327
+ end
328
+
329
+ # Convert object (array, hash, object, etc) to JSON string.
330
+ # @param [Object] model object to be converted into JSON string
331
+ # @return [String] JSON string representation of the object
332
+ def object_to_http_body(model)
333
+ return model if model.nil? || model.is_a?(String)
334
+ local_body = nil
335
+ if model.is_a?(Array)
336
+ local_body = model.map { |m| object_to_hash(m) }
337
+ else
338
+ local_body = object_to_hash(model)
339
+ end
340
+ local_body.to_json
341
+ end
342
+
343
+ # Convert object(non-array) to hash.
344
+ # @param [Object] obj object to be converted into JSON string
345
+ # @return [String] JSON string representation of the object
346
+ def object_to_hash(obj)
347
+ if obj.respond_to?(:to_hash)
348
+ obj.to_hash
349
+ else
350
+ obj
351
+ end
352
+ end
353
+
354
+ # Build parameter value according to the given collection format.
355
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
356
+ def build_collection_param(param, collection_format)
357
+ case collection_format
358
+ when :csv
359
+ param.join(',')
360
+ when :ssv
361
+ param.join(' ')
362
+ when :tsv
363
+ param.join("\t")
364
+ when :pipes
365
+ param.join('|')
366
+ when :multi
367
+ # return the array directly as typhoeus will handle it as expected
368
+ param
369
+ else
370
+ fail "unknown collection format: #{collection_format.inspect}"
371
+ end
372
+ end
373
+ end
374
+ end
@@ -0,0 +1,45 @@
1
+ module FCP
2
+ class ApiError < StandardError
3
+ attr_reader :code, :response_headers, :response_body
4
+
5
+ # Usage examples:
6
+ # ApiError.new
7
+ # ApiError.new("message")
8
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
9
+ # ApiError.new(:code => 404, :message => "Not Found")
10
+ def initialize(arg = nil)
11
+ if arg.is_a? Hash
12
+ if arg.key?(:message) || arg.key?('message')
13
+ super(arg[:message] || arg['message'])
14
+ else
15
+ super arg
16
+ end
17
+
18
+ arg.each do |k, v|
19
+ instance_variable_set "@#{k}", v
20
+ end
21
+ else
22
+ super arg
23
+ end
24
+ end
25
+
26
+ # Override to_s to display a friendly error message
27
+ def to_s
28
+ message
29
+ end
30
+
31
+ def message
32
+ if @message.nil?
33
+ msg = "Error message: the server returns an error"
34
+ else
35
+ msg = @message
36
+ end
37
+
38
+ msg += "\nHTTP status code: #{code}" if code
39
+ msg += "\nResponse headers: #{response_headers}" if response_headers
40
+ msg += "\nResponse body: #{response_body}" if response_body
41
+
42
+ msg
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,236 @@
1
+ module FCP
2
+ class Configuration
3
+ # Defines url scheme
4
+ attr_accessor :scheme
5
+
6
+ # Defines url host
7
+ attr_accessor :host
8
+
9
+ # Defines url base path
10
+ attr_accessor :base_path
11
+
12
+ # Defines API keys used with API Key authentications.
13
+ #
14
+ # @return [Hash] key: parameter name, value: parameter value (API key)
15
+ #
16
+ # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
17
+ # config.api_key['api_key'] = 'xxx'
18
+ attr_accessor :api_key
19
+
20
+ # Defines API key prefixes used with API Key authentications.
21
+ #
22
+ # @return [Hash] key: parameter name, value: API key prefix
23
+ #
24
+ # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
25
+ # config.api_key_prefix['api_key'] = 'Token'
26
+ attr_accessor :api_key_prefix
27
+
28
+ # Defines the username used with HTTP basic authentication.
29
+ #
30
+ # @return [String]
31
+ attr_accessor :username
32
+
33
+ # Defines the password used with HTTP basic authentication.
34
+ #
35
+ # @return [String]
36
+ attr_accessor :password
37
+
38
+ # Defines the access token (Bearer) used with OAuth2.
39
+ attr_accessor :access_token
40
+
41
+ # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
42
+ # details will be logged with `logger.debug` (see the `logger` attribute).
43
+ # Default to false.
44
+ #
45
+ # @return [true, false]
46
+ attr_accessor :debugging
47
+
48
+ # Defines the logger used for debugging.
49
+ # Default to `Rails.logger` (when in Rails) or logging to STDOUT.
50
+ #
51
+ # @return [#debug]
52
+ attr_accessor :logger
53
+
54
+ # Defines the temporary folder to store downloaded files
55
+ # (for API endpoints that have file response).
56
+ # Default to use `Tempfile`.
57
+ #
58
+ # @return [String]
59
+ attr_accessor :temp_folder_path
60
+
61
+ # The time limit for HTTP request in seconds.
62
+ # Default to 0 (never times out).
63
+ attr_accessor :timeout
64
+
65
+ # Set this to false to skip client side validation in the operation.
66
+ # Default to true.
67
+ # @return [true, false]
68
+ attr_accessor :client_side_validation
69
+
70
+ ### TLS/SSL setting
71
+ # Set this to false to skip verifying SSL certificate when calling API from https server.
72
+ # Default to true.
73
+ #
74
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
75
+ #
76
+ # @return [true, false]
77
+ attr_accessor :verify_ssl
78
+
79
+ ### TLS/SSL setting
80
+ # Set this to false to skip verifying SSL host name
81
+ # Default to true.
82
+ #
83
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
84
+ #
85
+ # @return [true, false]
86
+ attr_accessor :verify_ssl_host
87
+
88
+ ### TLS/SSL setting
89
+ # Set this to customize the certificate file to verify the peer.
90
+ #
91
+ # @return [String] the path to the certificate file
92
+ #
93
+ # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
94
+ # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
95
+ attr_accessor :ssl_ca_cert
96
+
97
+ ### TLS/SSL setting
98
+ # Client certificate file (for client certificate)
99
+ attr_accessor :cert_file
100
+
101
+ ### TLS/SSL setting
102
+ # Client private key file (for client certificate)
103
+ attr_accessor :key_file
104
+
105
+ # Set this to customize parameters encoding of array parameter with multi collectionFormat.
106
+ # Default to nil.
107
+ #
108
+ # @see The params_encoding option of Ethon. Related source code:
109
+ # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96
110
+ attr_accessor :params_encoding
111
+
112
+ attr_accessor :inject_format
113
+
114
+ attr_accessor :force_ending_format
115
+
116
+ def initialize
117
+ @scheme = 'https'
118
+ @host = 'api.firstclasspostcodes.com'
119
+ @base_path = '/data'
120
+ @api_key = {}
121
+ @api_key_prefix = {}
122
+ @timeout = 0
123
+ @client_side_validation = true
124
+ @verify_ssl = true
125
+ @verify_ssl_host = true
126
+ @params_encoding = nil
127
+ @cert_file = nil
128
+ @key_file = nil
129
+ @debugging = false
130
+ @inject_format = false
131
+ @force_ending_format = false
132
+ @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
133
+
134
+ yield(self) if block_given?
135
+ end
136
+
137
+ # The default Configuration object.
138
+ def self.default
139
+ @@default ||= Configuration.new
140
+ end
141
+
142
+ def configure
143
+ yield(self) if block_given?
144
+ end
145
+
146
+ def scheme=(scheme)
147
+ # remove :// from scheme
148
+ @scheme = scheme.sub(/:\/\//, '')
149
+ end
150
+
151
+ def host=(host)
152
+ # remove http(s):// and anything after a slash
153
+ @host = host.sub(/https?:\/\//, '').split('/').first
154
+ end
155
+
156
+ def base_path=(base_path)
157
+ # Add leading and trailing slashes to base_path
158
+ @base_path = "/#{base_path}".gsub(/\/+/, '/')
159
+ @base_path = '' if @base_path == '/'
160
+ end
161
+
162
+ def base_url
163
+ "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
164
+ end
165
+
166
+ # Gets API key (with prefix if set).
167
+ # @param [String] param_name the parameter name of API key auth
168
+ def api_key_with_prefix(param_name)
169
+ if @api_key_prefix[param_name]
170
+ "#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
171
+ else
172
+ @api_key[param_name]
173
+ end
174
+ end
175
+
176
+ # Gets Basic Auth token string
177
+ def basic_auth_token
178
+ 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
179
+ end
180
+
181
+ # Returns Auth Settings hash for api client.
182
+ def auth_settings
183
+ {
184
+ 'Authorizer' =>
185
+ {
186
+ type: 'api_key',
187
+ in: 'header',
188
+ key: 'X-Api-Key',
189
+ value: api_key_with_prefix('X-Api-Key')
190
+ },
191
+ }
192
+ end
193
+
194
+ # Returns an array of Server setting
195
+ def server_settings
196
+ [
197
+ {
198
+ url: "https://api.firstclasspostcodes.com/data",
199
+ description: "No descriptoin provided",
200
+ }
201
+ ]
202
+ end
203
+
204
+ # Returns URL based on server settings
205
+ #
206
+ # @param index array index of the server settings
207
+ # @param variables hash of variable and the corresponding value
208
+ def server_url(index, variables = {})
209
+ servers = server_settings
210
+
211
+ # check array index out of bound
212
+ if (index < 0 || index >= servers.size)
213
+ fail ArgumentError, "Invalid index #{index} when selecting the server. Must be less than #{servers.size}"
214
+ end
215
+
216
+ server = servers[index]
217
+ url = server[:url]
218
+
219
+ # go through variable and assign a value
220
+ server[:variables].each do |name, variable|
221
+ if variables.key?(name)
222
+ if (server[:variables][name][:enum_values].include? variables[name])
223
+ url.gsub! "{" + name.to_s + "}", variables[name]
224
+ else
225
+ fail ArgumentError, "The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}."
226
+ end
227
+ else
228
+ # use default value
229
+ url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value]
230
+ end
231
+ end
232
+
233
+ url
234
+ end
235
+ end
236
+ end