lib/translator_text/client.rb in translator-text-0.2.0 vs lib/translator_text/client.rb in translator-text-0.3.0
- old
+ new
@@ -1,23 +1,33 @@
+# frozen_string_literal: true
+
require 'json'
require 'securerandom'
require 'httparty'
module TranslatorText
class Client
include HTTParty
format :json
- base_uri 'https://api.cognitive.microsofttranslator.com'.freeze
- API_VERSION = '3.0'.freeze
+ base_uri 'https://api.cognitive.microsofttranslator.com'
+ API_VERSION = '3.0'
+ query_string_normalizer proc { |query|
+ query.map do |key, value|
+ Array(value).map { |v| "#{key}=#{v}" }
+ end.join('&')
+ }
+
# Initialize the client
# @since 1.0.0
#
# @param api_key [String] the Cognitive Services API Key
- def initialize(api_key)
+ # @param api_region [String] the Cognitive Services API Region
+ def initialize(api_key, api_region = nil)
@api_key = api_key
+ @api_region = api_region
end
# Translate a group of sentences.
#
# The following limitations apply:
@@ -31,11 +41,11 @@
# @return [Array<TranslatorText::Types::TranslationResult>] the translation results
def translate(sentences, to:, **options)
results = post(
'/translate',
body: build_sentences(sentences).to_json,
- query: Hash[to: to, **options]
+ query: { to:, **options }
)
results.map { |r| Types::TranslationResult.new(r) }
end
@@ -66,11 +76,11 @@
end
end
def post(path, params)
options = {
- headers: headers,
+ headers:,
query: {}
}.merge(params)
options[:query][:'api-version'] = API_VERSION
@@ -102,11 +112,12 @@
end
def headers
{
'Ocp-Apim-Subscription-Key' => @api_key,
+ 'Ocp-Apim-Subscription-Region' => @api_region,
'X-ClientTraceId' => SecureRandom.uuid,
'Content-type' => 'application/json'
- }
+ }.compact
end
end
end