Skip to content

Commit 8c0dba6

Browse files
committed
Add prefix for X-Opaque-Id on initializer
1 parent db8af33 commit 8c0dba6

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

elasticsearch-transport/lib/elasticsearch/transport/client.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ class Client
8787
#
8888
# @option api_key [String, Hash] :api_key Use API Key Authentication, either the base64 encoding of `id` and `api_key`
8989
# joined by a colon as a String, or a hash with the `id` and `api_key` values.
90+
# @option opaque_id_prefix [String] :opaque_id_prefix set a prefix for X-Opaque-Id when initializing the client. This
91+
# will be prepended to the id you set before each request if you're using X-Opaque-Id
9092
#
9193
# @yield [faraday] Access and configure the `Faraday::Connection` instance directly with a block
9294
#
@@ -114,6 +116,7 @@ def initialize(arguments={}, &block)
114116
DEFAULT_HOST)
115117

116118
@send_get_body_as = @arguments[:send_get_body_as] || 'GET'
119+
@opaque_id_prefix = @arguments[:opaque_id_prefix] || nil
117120

118121
if @arguments[:request_timeout]
119122
@arguments[:transport_options][:request] = { timeout: @arguments[:request_timeout] }
@@ -148,7 +151,8 @@ def perform_request(method, path, params = {}, body = nil, headers = nil)
148151
method = @send_get_body_as if 'GET' == method && body
149152
if @opaque_id
150153
headers = {} if headers.nil?
151-
headers.merge!('X-Opaque-Id' => @opaque_id)
154+
opaque_id = @opaque_id_prefix ? "#{@opaque_id_prefix}#{@opaque_id}" : @opaque_id
155+
headers.merge!('X-Opaque-Id' => opaque_id)
152156
@opaque_id = nil # Remove Opaque id after each request
153157
end
154158
transport.perform_request(method, path, params, body, headers)

elasticsearch-transport/spec/elasticsearch/transport/client_spec.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -667,6 +667,24 @@
667667
expect(client.perform_request('GET', '/').headers).not_to include('x-opaque-id')
668668
end
669669
end
670+
671+
context 'when an x-opaque-id prefix is set on initialization' do
672+
let(:prefix) { 'elastic_cloud' }
673+
let(:client) do
674+
described_class.new(host: hosts, opaque_id_prefix: prefix)
675+
end
676+
677+
it 'uses x-opaque-id on a request' do
678+
client.opaque_id = '12345'
679+
expect(client.perform_request('GET', '/').headers['x-opaque-id']).to eq("#{prefix}12345")
680+
end
681+
682+
it 'deletes x-opaque-id on a second request' do
683+
client.opaque_id = 'asdfg'
684+
expect(client.perform_request('GET', '/').headers['x-opaque-id']).to eq("#{prefix}_asdfg")
685+
expect(client.perform_request('GET', '/').headers).not_to include('x-opaque-id')
686+
end
687+
end
670688
end
671689

672690
context 'when the client connects to Elasticsearch' do

0 commit comments

Comments
 (0)