cns_openapi_ruby_client 1.0.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.
Files changed (37) hide show
  1. checksums.yaml +7 -0
  2. data/Gemfile +9 -0
  3. data/Gemfile.lock +81 -0
  4. data/README.md +123 -0
  5. data/Rakefile +10 -0
  6. data/cns_openapi_ruby_client.gemspec +39 -0
  7. data/docs/CorporateType.md +15 -0
  8. data/docs/Corporation.md +76 -0
  9. data/docs/CorporationsApi.md +101 -0
  10. data/docs/CorrectCodeType.md +15 -0
  11. data/docs/ProcessCodeType.md +15 -0
  12. data/docs/Response.md +26 -0
  13. data/docs/ResponseWrapper.md +18 -0
  14. data/git_push.sh +58 -0
  15. data/lib/cns_openapi_ruby_client.rb +46 -0
  16. data/lib/cns_openapi_ruby_client/api/corporations_api.rb +168 -0
  17. data/lib/cns_openapi_ruby_client/api_client.rb +383 -0
  18. data/lib/cns_openapi_ruby_client/api_error.rb +57 -0
  19. data/lib/cns_openapi_ruby_client/configuration.rb +277 -0
  20. data/lib/cns_openapi_ruby_client/models/corporate_type.rb +45 -0
  21. data/lib/cns_openapi_ruby_client/models/corporation.rb +606 -0
  22. data/lib/cns_openapi_ruby_client/models/correct_code_type.rb +37 -0
  23. data/lib/cns_openapi_ruby_client/models/process_code_type.rb +45 -0
  24. data/lib/cns_openapi_ruby_client/models/response.rb +286 -0
  25. data/lib/cns_openapi_ruby_client/models/response_wrapper.rb +223 -0
  26. data/lib/cns_openapi_ruby_client/version.rb +15 -0
  27. data/spec/api/corporations_api_spec.rb +57 -0
  28. data/spec/api_client_spec.rb +197 -0
  29. data/spec/configuration_spec.rb +42 -0
  30. data/spec/models/corporate_type_spec.rb +28 -0
  31. data/spec/models/corporation_spec.rb +220 -0
  32. data/spec/models/correct_code_type_spec.rb +28 -0
  33. data/spec/models/process_code_type_spec.rb +28 -0
  34. data/spec/models/response_spec.rb +58 -0
  35. data/spec/models/response_wrapper_spec.rb +34 -0
  36. data/spec/spec_helper.rb +111 -0
  37. metadata +148 -0
@@ -0,0 +1,15 @@
1
+ # CnsOpenapiRubyClient::CorrectCodeType
2
+
3
+ ## Properties
4
+
5
+ | Name | Type | Description | Notes |
6
+ | ---- | ---- | ----------- | ----- |
7
+
8
+ ## Example
9
+
10
+ ```ruby
11
+ require 'cns_openapi_ruby_client'
12
+
13
+ instance = CnsOpenapiRubyClient::CorrectCodeType.new()
14
+ ```
15
+
@@ -0,0 +1,15 @@
1
+ # CnsOpenapiRubyClient::ProcessCodeType
2
+
3
+ ## Properties
4
+
5
+ | Name | Type | Description | Notes |
6
+ | ---- | ---- | ----------- | ----- |
7
+
8
+ ## Example
9
+
10
+ ```ruby
11
+ require 'cns_openapi_ruby_client'
12
+
13
+ instance = CnsOpenapiRubyClient::ProcessCodeType.new()
14
+ ```
15
+
data/docs/Response.md ADDED
@@ -0,0 +1,26 @@
1
+ # CnsOpenapiRubyClient::Response
2
+
3
+ ## Properties
4
+
5
+ | Name | Type | Description | Notes |
6
+ | ---- | ---- | ----------- | ----- |
7
+ | **last_update_date** | **String** | 最終更新年月日 | |
8
+ | **count** | **Integer** | 総件数 | |
9
+ | **divide_number** | **Integer** | 分割されたファイルの通し番号(分子)を表すデータ項目。 | |
10
+ | **divide_size** | **Integer** | 分割されたファイルの総数(分母)にあたるデータ項目。 | |
11
+ | **corporation** | [**Array<Corporation>**](Corporation.md) | | |
12
+
13
+ ## Example
14
+
15
+ ```ruby
16
+ require 'cns_openapi_ruby_client'
17
+
18
+ instance = CnsOpenapiRubyClient::Response.new(
19
+ last_update_date: 2017-05-10,
20
+ count: 100,
21
+ divide_number: 1,
22
+ divide_size: 1,
23
+ corporation: null
24
+ )
25
+ ```
26
+
@@ -0,0 +1,18 @@
1
+ # CnsOpenapiRubyClient::ResponseWrapper
2
+
3
+ ## Properties
4
+
5
+ | Name | Type | Description | Notes |
6
+ | ---- | ---- | ----------- | ----- |
7
+ | **corporations** | [**Response**](Response.md) | | |
8
+
9
+ ## Example
10
+
11
+ ```ruby
12
+ require 'cns_openapi_ruby_client'
13
+
14
+ instance = CnsOpenapiRubyClient::ResponseWrapper.new(
15
+ corporations: null
16
+ )
17
+ ```
18
+
data/git_push.sh ADDED
@@ -0,0 +1,58 @@
1
+ #!/bin/sh
2
+ # ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
3
+ #
4
+ # Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com"
5
+
6
+ git_user_id=$1
7
+ git_repo_id=$2
8
+ release_note=$3
9
+ git_host=$4
10
+
11
+ if [ "$git_host" = "" ]; then
12
+ git_host="github.com"
13
+ echo "[INFO] No command line input provided. Set \$git_host to $git_host"
14
+ fi
15
+
16
+ if [ "$git_user_id" = "" ]; then
17
+ git_user_id="GIT_USER_ID"
18
+ echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
19
+ fi
20
+
21
+ if [ "$git_repo_id" = "" ]; then
22
+ git_repo_id="GIT_REPO_ID"
23
+ echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
24
+ fi
25
+
26
+ if [ "$release_note" = "" ]; then
27
+ release_note="Minor update"
28
+ echo "[INFO] No command line input provided. Set \$release_note to $release_note"
29
+ fi
30
+
31
+ # Initialize the local directory as a Git repository
32
+ git init
33
+
34
+ # Adds the files in the local repository and stages them for commit.
35
+ git add .
36
+
37
+ # Commits the tracked changes and prepares them to be pushed to a remote repository.
38
+ git commit -m "$release_note"
39
+
40
+ # Sets the new remote
41
+ git_remote=`git remote`
42
+ if [ "$git_remote" = "" ]; then # git remote not defined
43
+
44
+ if [ "$GIT_TOKEN" = "" ]; then
45
+ echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
46
+ git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
47
+ else
48
+ git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git
49
+ fi
50
+
51
+ fi
52
+
53
+ git pull origin master
54
+
55
+ # Pushes (Forces) the changes in the local repository up to the remote repository
56
+ echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
57
+ git push origin master 2>&1 | grep -v 'To https'
58
+
@@ -0,0 +1,46 @@
1
+ =begin
2
+ #Corporate number system API v4
3
+
4
+ #Corporate number system API v4
5
+
6
+ The version of the OpenAPI document: 1.0.0
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ OpenAPI Generator version: 5.0.1
10
+
11
+ =end
12
+
13
+ # Common files
14
+ require 'cns_openapi_ruby_client/api_client'
15
+ require 'cns_openapi_ruby_client/api_error'
16
+ require 'cns_openapi_ruby_client/version'
17
+ require 'cns_openapi_ruby_client/configuration'
18
+
19
+ # Models
20
+ require 'cns_openapi_ruby_client/models/corporate_type'
21
+ require 'cns_openapi_ruby_client/models/corporation'
22
+ require 'cns_openapi_ruby_client/models/correct_code_type'
23
+ require 'cns_openapi_ruby_client/models/process_code_type'
24
+ require 'cns_openapi_ruby_client/models/response'
25
+ require 'cns_openapi_ruby_client/models/response_wrapper'
26
+
27
+ # APIs
28
+ require 'cns_openapi_ruby_client/api/corporations_api'
29
+
30
+ module CnsOpenapiRubyClient
31
+ class << self
32
+ # Customize default settings for the SDK using block.
33
+ # CnsOpenapiRubyClient.configure do |config|
34
+ # config.username = "xxx"
35
+ # config.password = "xxx"
36
+ # end
37
+ # If no block given, return the default Configuration object.
38
+ def configure
39
+ if block_given?
40
+ yield(Configuration.default)
41
+ else
42
+ Configuration.default
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,168 @@
1
+ =begin
2
+ #Corporate number system API v4
3
+
4
+ #Corporate number system API v4
5
+
6
+ The version of the OpenAPI document: 1.0.0
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ OpenAPI Generator version: 5.0.1
10
+
11
+ =end
12
+
13
+ require 'cgi'
14
+
15
+ module CnsOpenapiRubyClient
16
+ class CorporationsApi
17
+ attr_accessor :api_client
18
+
19
+ def initialize(api_client = ApiClient.default)
20
+ @api_client = api_client
21
+ end
22
+ # 法人名を指定しリクエストすることで、指定した法人名の基本3情報及び付随する情報を取得することができます。
23
+ # 法人名による法人情報の取得
24
+ # @param name [String] 取得の対象とする法人名を URL エンコード(UTF-8)した値をセットします。
25
+ # @param type [String] リクエストに対して応答するデータのファイル形式と文字コードを指定します。
26
+ # @param [Hash] opts the optional parameters
27
+ # @option opts [Integer] :mode 検索方式を指定できます。 指定しない場合は、「1」(前方一致検索)で処理します。 (default to 1)
28
+ # @option opts [Integer] :target 検索対象を指定できます。 指定しない場合は、「1」(JIS 第一・第二水準)で処理します。 (default to 1)
29
+ # @option opts [String] :address 国内所在地の都道府県コード又は 都道府県コードと市区町村コードを組み合わせたコードのいずれかを指定できます。 市区町村コードのみではエラー(エラーコード 051)となります。
30
+ # @option opts [String] :kind 法人種別を指定できます。
31
+ # @option opts [Integer] :change 法人名や所在地の変更があった法人等に ついて過去の情報を含めて検索するかどうかを指定できます。 (default to 0)
32
+ # @option opts [Integer] :close 登記記録の閉鎖等があった法人等の情報を取得するかどうかを指定できます。 (default to 1)
33
+ # @option opts [String] :from 取得の対象とする法人番号指定年月日の開始日を指定できます。
34
+ # @option opts [String] :to 取得の対象とする法人番号指定年月日の終了日を指定できます。
35
+ # @option opts [Integer] :divide 分割番号を指定できます。 指定しない場合は、「1」で処理します。
36
+ # @return [ResponseWrapper]
37
+ def get_corporations(name, type, opts = {})
38
+ data, _status_code, _headers = get_corporations_with_http_info(name, type, opts)
39
+ data
40
+ end
41
+
42
+ # 法人名を指定しリクエストすることで、指定した法人名の基本3情報及び付随する情報を取得することができます。
43
+ # 法人名による法人情報の取得
44
+ # @param name [String] 取得の対象とする法人名を URL エンコード(UTF-8)した値をセットします。
45
+ # @param type [String] リクエストに対して応答するデータのファイル形式と文字コードを指定します。
46
+ # @param [Hash] opts the optional parameters
47
+ # @option opts [Integer] :mode 検索方式を指定できます。 指定しない場合は、「1」(前方一致検索)で処理します。
48
+ # @option opts [Integer] :target 検索対象を指定できます。 指定しない場合は、「1」(JIS 第一・第二水準)で処理します。
49
+ # @option opts [String] :address 国内所在地の都道府県コード又は 都道府県コードと市区町村コードを組み合わせたコードのいずれかを指定できます。 市区町村コードのみではエラー(エラーコード 051)となります。
50
+ # @option opts [String] :kind 法人種別を指定できます。
51
+ # @option opts [Integer] :change 法人名や所在地の変更があった法人等に ついて過去の情報を含めて検索するかどうかを指定できます。
52
+ # @option opts [Integer] :close 登記記録の閉鎖等があった法人等の情報を取得するかどうかを指定できます。
53
+ # @option opts [String] :from 取得の対象とする法人番号指定年月日の開始日を指定できます。
54
+ # @option opts [String] :to 取得の対象とする法人番号指定年月日の終了日を指定できます。
55
+ # @option opts [Integer] :divide 分割番号を指定できます。 指定しない場合は、「1」で処理します。
56
+ # @return [Array<(ResponseWrapper, Integer, Hash)>] ResponseWrapper data, response status code and response headers
57
+ def get_corporations_with_http_info(name, type, opts = {})
58
+ if @api_client.config.debugging
59
+ @api_client.config.logger.debug 'Calling API: CorporationsApi.get_corporations ...'
60
+ end
61
+ # verify the required parameter 'name' is set
62
+ if @api_client.config.client_side_validation && name.nil?
63
+ fail ArgumentError, "Missing the required parameter 'name' when calling CorporationsApi.get_corporations"
64
+ end
65
+ # verify the required parameter 'type' is set
66
+ if @api_client.config.client_side_validation && type.nil?
67
+ fail ArgumentError, "Missing the required parameter 'type' when calling CorporationsApi.get_corporations"
68
+ end
69
+ # verify enum value
70
+ allowable_values = ["12", "01", "02"]
71
+ if @api_client.config.client_side_validation && !allowable_values.include?(type)
72
+ fail ArgumentError, "invalid value for \"type\", must be one of #{allowable_values}"
73
+ end
74
+ allowable_values = [1, 2]
75
+ if @api_client.config.client_side_validation && opts[:'mode'] && !allowable_values.include?(opts[:'mode'])
76
+ fail ArgumentError, "invalid value for \"mode\", must be one of #{allowable_values}"
77
+ end
78
+ allowable_values = [1, 2, 3]
79
+ if @api_client.config.client_side_validation && opts[:'target'] && !allowable_values.include?(opts[:'target'])
80
+ fail ArgumentError, "invalid value for \"target\", must be one of #{allowable_values}"
81
+ end
82
+ pattern = Regexp.new(/[0-9]{2,5}/)
83
+ if @api_client.config.client_side_validation && !opts[:'address'].nil? && opts[:'address'] !~ pattern
84
+ fail ArgumentError, "invalid value for 'opts[:\"address\"]' when calling CorporationsApi.get_corporations, must conform to the pattern #{pattern}."
85
+ end
86
+
87
+ allowable_values = ["01", "02", "03", "04"]
88
+ if @api_client.config.client_side_validation && opts[:'kind'] && !allowable_values.include?(opts[:'kind'])
89
+ fail ArgumentError, "invalid value for \"kind\", must be one of #{allowable_values}"
90
+ end
91
+ allowable_values = [0, 1]
92
+ if @api_client.config.client_side_validation && opts[:'change'] && !allowable_values.include?(opts[:'change'])
93
+ fail ArgumentError, "invalid value for \"change\", must be one of #{allowable_values}"
94
+ end
95
+ allowable_values = [0, 1]
96
+ if @api_client.config.client_side_validation && opts[:'close'] && !allowable_values.include?(opts[:'close'])
97
+ fail ArgumentError, "invalid value for \"close\", must be one of #{allowable_values}"
98
+ end
99
+ pattern = Regexp.new(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)
100
+ if @api_client.config.client_side_validation && !opts[:'from'].nil? && opts[:'from'] !~ pattern
101
+ fail ArgumentError, "invalid value for 'opts[:\"from\"]' when calling CorporationsApi.get_corporations, must conform to the pattern #{pattern}."
102
+ end
103
+
104
+ pattern = Regexp.new(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)
105
+ if @api_client.config.client_side_validation && !opts[:'to'].nil? && opts[:'to'] !~ pattern
106
+ fail ArgumentError, "invalid value for 'opts[:\"to\"]' when calling CorporationsApi.get_corporations, must conform to the pattern #{pattern}."
107
+ end
108
+
109
+ if @api_client.config.client_side_validation && !opts[:'divide'].nil? && opts[:'divide'] > 99999
110
+ fail ArgumentError, 'invalid value for "opts[:"divide"]" when calling CorporationsApi.get_corporations, must be smaller than or equal to 99999.'
111
+ end
112
+
113
+ if @api_client.config.client_side_validation && !opts[:'divide'].nil? && opts[:'divide'] < 1
114
+ fail ArgumentError, 'invalid value for "opts[:"divide"]" when calling CorporationsApi.get_corporations, must be greater than or equal to 1.'
115
+ end
116
+
117
+ # resource path
118
+ local_var_path = '/name'
119
+
120
+ # query parameters
121
+ query_params = opts[:query_params] || {}
122
+ query_params[:'name'] = name
123
+ query_params[:'type'] = type
124
+ query_params[:'mode'] = opts[:'mode'] if !opts[:'mode'].nil?
125
+ query_params[:'target'] = opts[:'target'] if !opts[:'target'].nil?
126
+ query_params[:'address'] = opts[:'address'] if !opts[:'address'].nil?
127
+ query_params[:'kind'] = opts[:'kind'] if !opts[:'kind'].nil?
128
+ query_params[:'change'] = opts[:'change'] if !opts[:'change'].nil?
129
+ query_params[:'close'] = opts[:'close'] if !opts[:'close'].nil?
130
+ query_params[:'from'] = opts[:'from'] if !opts[:'from'].nil?
131
+ query_params[:'to'] = opts[:'to'] if !opts[:'to'].nil?
132
+ query_params[:'divide'] = opts[:'divide'] if !opts[:'divide'].nil?
133
+
134
+ # header parameters
135
+ header_params = opts[:header_params] || {}
136
+ # HTTP header 'Accept' (if needed)
137
+ header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json'])
138
+
139
+ # form parameters
140
+ form_params = opts[:form_params] || {}
141
+
142
+ # http body (model)
143
+ post_body = opts[:debug_body]
144
+
145
+ # return_type
146
+ return_type = opts[:debug_return_type] || 'ResponseWrapper'
147
+
148
+ # auth_names
149
+ auth_names = opts[:debug_auth_names] || ['id']
150
+
151
+ new_options = opts.merge(
152
+ :operation => :"CorporationsApi.get_corporations",
153
+ :header_params => header_params,
154
+ :query_params => query_params,
155
+ :form_params => form_params,
156
+ :body => post_body,
157
+ :auth_names => auth_names,
158
+ :return_type => return_type
159
+ )
160
+
161
+ data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
162
+ if @api_client.config.debugging
163
+ @api_client.config.logger.debug "API called: CorporationsApi#get_corporations\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
164
+ end
165
+ return data, status_code, headers
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,383 @@
1
+ =begin
2
+ #Corporate number system API v4
3
+
4
+ #Corporate number system API v4
5
+
6
+ The version of the OpenAPI document: 1.0.0
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ OpenAPI Generator version: 5.0.1
10
+
11
+ =end
12
+
13
+ require 'date'
14
+ require 'json'
15
+ require 'logger'
16
+ require 'tempfile'
17
+ require 'time'
18
+ require 'typhoeus'
19
+ require 'active_support/core_ext/hash'
20
+
21
+
22
+ module CnsOpenapiRubyClient
23
+ class ApiClient
24
+ # The Configuration object holding settings to be used in the API client.
25
+ attr_accessor :config
26
+
27
+ # Defines the headers to be used in HTTP requests of all API calls by default.
28
+ #
29
+ # @return [Hash]
30
+ attr_accessor :default_headers
31
+
32
+ # Initializes the ApiClient
33
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
34
+ def initialize(config = Configuration.default)
35
+ @config = config
36
+ @user_agent = "OpenAPI-Generator/#{VERSION}/ruby"
37
+ @default_headers = {
38
+ 'Content-Type' => 'application/json',
39
+ 'User-Agent' => @user_agent
40
+ }
41
+ end
42
+
43
+ def self.default
44
+ @@default ||= ApiClient.new
45
+ end
46
+
47
+ # Call an API with given options.
48
+ #
49
+ # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
50
+ # the data deserialized from response body (could be nil), response status code and response headers.
51
+ def call_api(http_method, path, opts = {})
52
+ request = build_request(http_method, path, opts)
53
+ response = request.run
54
+
55
+ if @config.debugging
56
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
57
+ end
58
+
59
+ unless response.success?
60
+ if response.timed_out?
61
+ fail ApiError.new('Connection timed out')
62
+ elsif response.code == 0
63
+ # Errors from libcurl will be made visible here
64
+ fail ApiError.new(:code => 0,
65
+ :message => response.return_message)
66
+ else
67
+ fail ApiError.new(:code => response.code,
68
+ :response_headers => response.headers,
69
+ :response_body => response.body),
70
+ response.status_message
71
+ end
72
+ end
73
+
74
+ if opts[:return_type]
75
+ data = deserialize(response, opts[:return_type])
76
+ else
77
+ data = nil
78
+ end
79
+ return data, response.code, response.headers
80
+ end
81
+
82
+ # Builds the HTTP request
83
+ #
84
+ # @param [String] http_method HTTP method/verb (e.g. POST)
85
+ # @param [String] path URL path (e.g. /account/new)
86
+ # @option opts [Hash] :header_params Header parameters
87
+ # @option opts [Hash] :query_params Query parameters
88
+ # @option opts [Hash] :form_params Query parameters
89
+ # @option opts [Object] :body HTTP body (JSON/XML)
90
+ # @return [Typhoeus::Request] A Typhoeus Request
91
+ def build_request(http_method, path, opts = {})
92
+ url = build_request_url(path, opts)
93
+ http_method = http_method.to_sym.downcase
94
+
95
+ header_params = @default_headers.merge(opts[:header_params] || {})
96
+ query_params = opts[:query_params] || {}
97
+ form_params = opts[:form_params] || {}
98
+
99
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
100
+
101
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
102
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
103
+
104
+ req_opts = {
105
+ :method => http_method,
106
+ :headers => header_params,
107
+ :params => query_params,
108
+ :params_encoding => @config.params_encoding,
109
+ :timeout => @config.timeout,
110
+ :ssl_verifypeer => @config.verify_ssl,
111
+ :ssl_verifyhost => _verify_ssl_host,
112
+ :sslcert => @config.cert_file,
113
+ :sslkey => @config.key_file,
114
+ :verbose => @config.debugging
115
+ }
116
+
117
+ # set custom cert, if provided
118
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
119
+
120
+ if [:post, :patch, :put, :delete].include?(http_method)
121
+ req_body = build_request_body(header_params, form_params, opts[:body])
122
+ req_opts.update :body => req_body
123
+ if @config.debugging
124
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
125
+ end
126
+ end
127
+
128
+ request = Typhoeus::Request.new(url, req_opts)
129
+ download_file(request) if opts[:return_type] == 'File'
130
+ request
131
+ end
132
+
133
+ # Builds the HTTP request body
134
+ #
135
+ # @param [Hash] header_params Header parameters
136
+ # @param [Hash] form_params Query parameters
137
+ # @param [Object] body HTTP body (JSON/XML)
138
+ # @return [String] HTTP body data in the form of string
139
+ def build_request_body(header_params, form_params, body)
140
+ # http form
141
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
142
+ header_params['Content-Type'] == 'multipart/form-data'
143
+ data = {}
144
+ form_params.each do |key, value|
145
+ case value
146
+ when ::File, ::Array, nil
147
+ # let typhoeus handle File, Array and nil parameters
148
+ data[key] = value
149
+ else
150
+ data[key] = value.to_s
151
+ end
152
+ end
153
+ elsif body
154
+ data = body.is_a?(String) ? body : body.to_json
155
+ else
156
+ data = nil
157
+ end
158
+ data
159
+ end
160
+
161
+ # Save response body into a file in (the defined) temporary folder, using the filename
162
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
163
+ # The response body is written to the file in chunks in order to handle files which
164
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
165
+ # process can use.
166
+ #
167
+ # @see Configuration#temp_folder_path
168
+ def download_file(request)
169
+ tempfile = nil
170
+ encoding = nil
171
+ request.on_headers do |response|
172
+ content_disposition = response.headers['Content-Disposition']
173
+ if content_disposition && content_disposition =~ /filename=/i
174
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
175
+ prefix = sanitize_filename(filename)
176
+ else
177
+ prefix = 'download-'
178
+ end
179
+ prefix = prefix + '-' unless prefix.end_with?('-')
180
+ encoding = response.body.encoding
181
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
182
+ @tempfile = tempfile
183
+ end
184
+ request.on_body do |chunk|
185
+ chunk.force_encoding(encoding)
186
+ tempfile.write(chunk)
187
+ end
188
+ request.on_complete do |response|
189
+ if tempfile
190
+ tempfile.close
191
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
192
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
193
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
194
+ "explicitly with `tempfile.delete`"
195
+ end
196
+ end
197
+ end
198
+
199
+ # Check if the given MIME is a JSON MIME.
200
+ # JSON MIME examples:
201
+ # application/json
202
+ # application/json; charset=UTF8
203
+ # APPLICATION/JSON
204
+ # */*
205
+ # @param [String] mime MIME
206
+ # @return [Boolean] True if the MIME is application/json
207
+ def xml_mime?(mime)
208
+ (mime == '*/*') || !(mime =~ /Application\/.*xml(?!p)(;.*)?/i).nil?
209
+ end
210
+
211
+ # Deserialize the response to the given return type.
212
+ #
213
+ # @param [Response] response HTTP response
214
+ # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
215
+ def deserialize(response, return_type)
216
+ body = response.body
217
+
218
+ # handle file downloading - return the File instance processed in request callbacks
219
+ # note that response body is empty when the file is written in chunks in request on_body callback
220
+ return @tempfile if return_type == 'File'
221
+
222
+ return nil if body.nil? || body.empty?
223
+
224
+ # return response body directly for String return type
225
+ return body if return_type == 'String'
226
+
227
+ # ensuring a default content type
228
+ content_type = response.headers['Content-Type'] || 'application/xml'
229
+ fail "Content-Type is not supported: #{content_type}" unless xml_mime?(content_type)
230
+
231
+ data = Hash.from_xml(body).deep_symbolize_keys
232
+
233
+ convert_to_type data, return_type
234
+ end
235
+
236
+ # Convert data to the given return type.
237
+ # @param [Object] data Data to be converted
238
+ # @param [String] return_type Return type
239
+ # @return [Mixed] Data in a particular type
240
+ def convert_to_type(data, return_type)
241
+ return nil if data.nil?
242
+ case return_type
243
+ when 'String'
244
+ data.to_s
245
+ when 'Integer'
246
+ data.to_i
247
+ when 'Float'
248
+ data.to_f
249
+ when 'Boolean'
250
+ data == true
251
+ when 'Time'
252
+ # parse date time (expecting ISO 8601 format)
253
+ Time.parse data
254
+ when 'Date'
255
+ # parse date time (expecting ISO 8601 format)
256
+ Date.parse data
257
+ when 'Object'
258
+ # generic object (usually a Hash), return directly
259
+ data
260
+ when /\AArray<(.+)>\z/
261
+ # e.g. Array<Pet>
262
+ sub_type = $1
263
+ data.map { |item| convert_to_type(item, sub_type) }
264
+ when /\AHash\<String, (.+)\>\z/
265
+ # e.g. Hash<String, Integer>
266
+ sub_type = $1
267
+ {}.tap do |hash|
268
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
269
+ end
270
+ else
271
+ # models (e.g. Pet) or oneOf
272
+ klass = CnsOpenapiRubyClient.const_get(return_type)
273
+ klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
274
+ end
275
+ end
276
+
277
+ # Sanitize filename by removing path.
278
+ # e.g. ../../sun.gif becomes sun.gif
279
+ #
280
+ # @param [String] filename the filename to be sanitized
281
+ # @return [String] the sanitized filename
282
+ def sanitize_filename(filename)
283
+ filename.gsub(/.*[\/\\]/, '')
284
+ end
285
+
286
+ def build_request_url(path, opts = {})
287
+ # Add leading and trailing slashes to path
288
+ path = "/#{path}".gsub(/\/+/, '/')
289
+ @config.base_url(opts[:operation]) + path
290
+ end
291
+
292
+ # Update hearder and query params based on authentication settings.
293
+ #
294
+ # @param [Hash] header_params Header parameters
295
+ # @param [Hash] query_params Query parameters
296
+ # @param [String] auth_names Authentication scheme name
297
+ def update_params_for_auth!(header_params, query_params, auth_names)
298
+ Array(auth_names).each do |auth_name|
299
+ auth_setting = @config.auth_settings[auth_name]
300
+ next unless auth_setting
301
+ case auth_setting[:in]
302
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
303
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
304
+ else fail ArgumentError, 'Authentication token must be in `query` or `header`'
305
+ end
306
+ end
307
+ end
308
+
309
+ # Sets user agent in HTTP header
310
+ #
311
+ # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
312
+ def user_agent=(user_agent)
313
+ @user_agent = user_agent
314
+ @default_headers['User-Agent'] = @user_agent
315
+ end
316
+
317
+ # Return Accept header based on an array of accepts provided.
318
+ # @param [Array] accepts array for Accept
319
+ # @return [String] the Accept header (e.g. application/json)
320
+ def select_header_accept(accepts)
321
+ return nil if accepts.nil? || accepts.empty?
322
+ # use JSON when present, otherwise use all of the provided
323
+ xml_accept = accepts.find { |s| xml_mime?(s) }
324
+ xml_accept || accepts.join(',')
325
+ end
326
+
327
+ # Return Content-Type header based on an array of content types provided.
328
+ # @param [Array] content_types array for Content-Type
329
+ # @return [String] the Content-Type header (e.g. application/json)
330
+ def select_header_content_type(content_types)
331
+ # use application/json by default
332
+ return 'application/xml' if content_types.nil? || content_types.empty?
333
+
334
+ xml_content_type = content_types.find { |s| xml_mime?(s) }
335
+ xml_content_type || content_types.first
336
+ end
337
+
338
+ # Convert object (array, hash, object, etc) to JSON string.
339
+ # @param [Object] model object to be converted into JSON string
340
+ # @return [String] JSON string representation of the object
341
+ def object_to_http_body(model)
342
+ return model if model.nil? || model.is_a?(String)
343
+ local_body = nil
344
+ if model.is_a?(Array)
345
+ local_body = model.map { |m| object_to_hash(m) }
346
+ else
347
+ local_body = object_to_hash(model)
348
+ end
349
+ local_body.to_json
350
+ end
351
+
352
+ # Convert object(non-array) to hash.
353
+ # @param [Object] obj object to be converted into JSON string
354
+ # @return [String] JSON string representation of the object
355
+ def object_to_hash(obj)
356
+ if obj.respond_to?(:to_hash)
357
+ obj.to_hash
358
+ else
359
+ obj
360
+ end
361
+ end
362
+
363
+ # Build parameter value according to the given collection format.
364
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
365
+ def build_collection_param(param, collection_format)
366
+ case collection_format
367
+ when :csv
368
+ param.join(',')
369
+ when :ssv
370
+ param.join(' ')
371
+ when :tsv
372
+ param.join("\t")
373
+ when :pipes
374
+ param.join('|')
375
+ when :multi
376
+ # return the array directly as typhoeus will handle it as expected
377
+ param
378
+ else
379
+ fail "unknown collection format: #{collection_format.inspect}"
380
+ end
381
+ end
382
+ end
383
+ end