fix(baileys): handle array response in on_whatsapp endpoint

The Baileys `/on-whatsapp` endpoint can return a bare JSON array instead
of a hash with a `data` key. Calling `Array#dig` with a string key
raises `TypeError (no implicit conversion of String into Integer)`,
causing a 500 error. Handle both response shapes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
gabrieljablonski 2026-03-20 16:41:22 -03:00
parent eb22a96ba5
commit 0da4c52ee8
2 changed files with 33 additions and 1 deletions

View File

@ -424,7 +424,9 @@ class Whatsapp::Providers::WhatsappBaileysService < Whatsapp::Providers::BaseSer
raise ProviderUnavailableError unless process_response(response)
response.parsed_response&.dig('data')&.first || { 'jid' => remote_jid, 'exists' => false }
result = response.parsed_response
result = result.is_a?(Array) ? result : result&.dig('data')
result&.first || { 'jid' => remote_jid, 'exists' => false }
end
def delete_message(recipient_id, message)

View File

@ -946,6 +946,36 @@ describe Whatsapp::Providers::WhatsappBaileysService do
end
end
context 'when response is an array instead of a hash' do
it 'handles the array response correctly' do
stub_request(:post, request_path)
.with(headers: stub_headers(whatsapp_channel), body: { jids: ["#{phone_number.delete('+')}@s.whatsapp.net"] }.to_json)
.to_return(
status: 200,
headers: { 'Content-Type' => 'application/json' },
body: [{ jid: "#{phone_number.delete('+')}@s.whatsapp.net", exists: true }].to_json
)
response = service.on_whatsapp(phone_number)
expect(response).to eq({ 'jid' => "#{phone_number.delete('+')}@s.whatsapp.net", 'exists' => true })
end
it 'returns default check response when array is empty' do
stub_request(:post, request_path)
.with(headers: stub_headers(whatsapp_channel), body: { jids: ["#{phone_number.delete('+')}@s.whatsapp.net"] }.to_json)
.to_return(
status: 200,
headers: { 'Content-Type' => 'application/json' },
body: [].to_json
)
response = service.on_whatsapp(phone_number)
expect(response).to eq({ 'jid' => "#{phone_number.delete('+')}@s.whatsapp.net", 'exists' => false })
end
end
context 'when response is unsuccessful' do
it 'raises ProviderUnavailableError and logs the error' do
stub_request(:post, request_path)