2020-06-07 17:00:56 +03:00

41 lines
1.0 KiB
Elixir

defmodule Localizator.Translator.Yandex do
@type text :: String.t()
@type locale :: String.t()
@type from :: locale
@type to :: locale
@type message :: String.t()
@behaviour Localizator.Translator.Base
@impl true
@spec detect(text) :: {:ok, locale} | {:error, message}
def detect(text) when is_bitstring(text) do
case YandexTranslate.detect(text) do
%{languageCode: locale} -> {:ok, locale}
%{} -> {:error, "Couldn't detect language"}
end
end
@impl true
@spec translate(text, to) :: {:ok, text} | {:error, message}
def translate(text, to, from \\ nil)
def translate(text, to, from) when is_bitstring(text) and is_bitstring(to) do
translator_response =
case from do
nil -> YandexTranslate.translate(text, to)
_ -> YandexTranslate.translate(text, to, from)
end
case translator_response do
%{translations: translations} ->
translations
|> List.first()
|> Map.fetch(:text)
%{message: message} ->
{:error, message}
end
end
end