Skip to content

Commit

Permalink
Merge pull request #44 from ioki-mobility/encoding-middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
rmehner committed Nov 25, 2021
2 parents 5f22b03 + df14f10 commit 8ee5912
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
10 changes: 7 additions & 3 deletions lib/ioki/http_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,22 @@ class HttpAdapter

def self.get(config)
::Faraday.new(config.api_base_url, headers: headers(config)) do |f|
f.request :json # encode req bodies as JSON
f.response :json # decode response bodies as JSON
f.adapter :net_http
f.request :authorization, 'Bearer', -> { config.api_token }

# The order of execution of the middleware is FiFo:
# 1) parsed as JSON (and implicitly is encoded properly as UTF-8)
# 2) logging occurs
if config.logger
f.response :logger, config.logger, config.logger_options do |logger|
logger.filter(/(X-Client-Secret: )(\w+)/, '\1[REMOVED]')
logger.filter(/(Authorization: )(\w+)/, '\1[REMOVED]')
logger.filter(/("token":")([^"]+)/, '\1[REMOVED]')
end
end
f.response :json # decode response bodies as JSON

f.request :json # encode req bodies as JSON
f.request :authorization, 'Bearer', -> { config.api_token }
end
end

Expand Down
20 changes: 19 additions & 1 deletion spec/ioki/http_adapter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
api_client_version: 'api_client_version',
api_token: 'SECRET_TOKEN',
language: :'en-BZ',
logger: logger
logger: logger,
logger_options: { headers: true, bodies: true }
)
end
let(:logger) { nil }
Expand Down Expand Up @@ -59,4 +60,21 @@
it { is_expected.to include 'X-Client-Version' => config.api_client_version }
it { is_expected.to include 'Authorization' => 'Bearer SECRET_TOKEN' }
end

describe 'encoding for logger' do
let(:logger) { instance_double(::Logger, 'logger') }

it 'uses the correct encoding from the Content-Type header' do
stub_request(:get, 'https://app.io.ki/api/platform/products').to_return(
status: 200,
body: [{ name: 'Grüne Höhe Wägen' }].to_json.force_encoding(Encoding::ASCII_8BIT),
headers: { 'Content-Type' => 'application/json; charset=utf-8' }
)
allow(logger).to receive(:info) do |*_args, &block|
body = block.call
expect(body.encoding).to eq(Encoding::UTF_8)
end
http_adapter.get('platform/products')
end
end
end

0 comments on commit 8ee5912

Please sign in to comment.