Skip to content

Instantly share code, notes, and snippets.

@ihumanable
Last active June 5, 2020 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ihumanable/f13abdf94212893a656cca72849c81a9 to your computer and use it in GitHub Desktop.
Save ihumanable/f13abdf94212893a656cca72849c81a9 to your computer and use it in GitHub Desktop.
Refactored Twilio Processing Code
defmodule Twilio.Helper do
defmodule PhoneNumber do
alias Twilio.Helper.{CallerInfo, CarrierInfo}
defstruct [:carrier_type,
:carrier_name,
:country_code,
:national_format,
:caller_name,
:caller_type,
:mobile_country_code,
:mobile_network_code]
def from_response(response, %CallerInfo{} = caller_info, %CarrierInfo{} = carrier_info) do
%__MODULE__{
carrier_type: carrier_info.type,
carrier_name: carrier_info.name,
country_code: response.country_code,
national_format: response.national_format,
caller_name: caller_info.caller_name,
caller_type: caller_info.caller_type,
mobile_country_code: carrier_info.mobile_country_code,
mobile_network_code: carrier_info.mobile_network_code
}
end
end
defmodule CallerInfo do
defstruct [:caller_name, :caller_type]
def from_add_on_result(add_on_result) do
%__MODULE__{
caller_name: add_on_result["caller_name"],
caller_type: add_on_result["caller_type"]
}
end
end
defmodule CarrierInfo do
defstruct [:mobile_country_code, :mobile_network_code, :name, :type]
def from_add_on_result(add_on_result) do
%__MODULE__{
mobile_country_code: add_on_result["mobile_country_code"],
mobile_network_code: add_on_result["mobile_network_code"],
name: add_on_result["name"],
type: add_on_result["type"]
}
end
end
def lookup_phone_number(params) do
case client().lookup_phone_number(params) do
{:error, _} ->
@not_found
{:ok, response} ->
caller_info = caller_info(response.add_ons)
carrier_info = carrier_info(response.add_ons)
PhoneNumber.from_response(response, caller_info, carrier_info)
end
end
def caller_info(add_ons) do
add_on_result = add_ons["results"]["twilio_caller_name"]["result"]["caller_name"]
if Enum.empty?(add_on_result) do
%CallerInfo{}
else
CallerInfo.from_add_on_result(add_on_result)
end
end
def carrier_info(add_ons) do
add_on_result = add_ons["results"]["twilio_carrier_info"]["result"]["carrier"]
if Enum.empty?(add_on_result) do
%CarrierInfo{}
else
CarrierInfo.from_add_on_result(add_on_result)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment