|
| 1 | +require 'json' |
| 2 | +require 'net/http' |
| 3 | +require 'uri' |
| 4 | + |
| 5 | +# This helper is used as a workaround to enable legacy search in tests. |
| 6 | +# See https://github.com/meilisearch/meilisearch/issues/6482 |
| 7 | + |
| 8 | +module LegacySearchHelper |
| 9 | + LEGACY_SEARCH_ENDPOINT = '/experimental-features'.freeze |
| 10 | + private_constant :LEGACY_SEARCH_ENDPOINT |
| 11 | + |
| 12 | + def enable_meilisearch_legacy_search! |
| 13 | + update_meilisearch_legacy_search!(enabled: true) |
| 14 | + end |
| 15 | + |
| 16 | + def disable_meilisearch_legacy_search! |
| 17 | + update_meilisearch_legacy_search!(enabled: false) |
| 18 | + end |
| 19 | + |
| 20 | + private |
| 21 | + |
| 22 | + def update_meilisearch_legacy_search!(enabled:) |
| 23 | + config = Meilisearch::Rails.configuration |
| 24 | + host = config.fetch(:meilisearch_url) |
| 25 | + api_key = config[:meilisearch_api_key] |
| 26 | + action = enabled ? 'enable' : 'disable' |
| 27 | + |
| 28 | + uri = URI.parse("#{host.chomp('/')}#{LEGACY_SEARCH_ENDPOINT}") |
| 29 | + request = Net::HTTP::Patch.new(uri) |
| 30 | + request['Content-Type'] = 'application/json' |
| 31 | + request['Authorization'] = "Bearer #{api_key}" if api_key.present? |
| 32 | + request.body = { legacySearch: enabled }.to_json |
| 33 | + |
| 34 | + response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| |
| 35 | + http.request(request) |
| 36 | + end |
| 37 | + |
| 38 | + return if response.is_a?(Net::HTTPSuccess) |
| 39 | + |
| 40 | + raise "Failed to #{action} Meilisearch legacy search in tests: " \ |
| 41 | + "HTTP #{response.code} #{response.message}. Response body: #{response.body}" |
| 42 | + rescue KeyError => e |
| 43 | + raise "Missing Meilisearch test configuration: #{e.message}" |
| 44 | + rescue StandardError => e |
| 45 | + raise if e.message.start_with?("Failed to #{action} Meilisearch legacy search in tests:") |
| 46 | + |
| 47 | + raise "Failed to #{action} Meilisearch legacy search in tests: #{e.class}: #{e.message}" |
| 48 | + end |
| 49 | +end |
0 commit comments