Current section
Files
Jump to
Current section
Files
lib/numverify.ex
defmodule Numverify do
@moduledoc """
Verify numbers through the [Numverify](http://numverify.com/) API.
A valid Numverify API key must be used to do anything. It can either be in the
application configuration under `:key` or as an environment variable under the
name of `NUMVERIFY_KEY`.
"""
alias Numverify.Gateway
@doc """
Validate the given `opts`, a map of inputs to the API.
A `number` field must be present.
Refer to the Numverify [documentation](https://numverify.com/documentation) for
more information.
"""
@spec validate(map) :: {:ok, map} | {:error, integer, String.t}
def validate(opts) do
url = "validate?#{opts |> URI.encode_query}"
url
|> Gateway.get
|> process_response
end
@doc """
Returns a map of countries and their telephone codes.
"""
@spec countries :: {:ok, map}
def countries do
"countries"
|> Gateway.get
|> process_response
end
@doc """
Convenience function to quickly test the validity of a number.
Returns `true` if the number is valid, `false` if not, and `nil` if there was
an error.
"""
@spec is_valid?(integer | String.t) :: boolean
def is_valid?(number) do
case validate(%{number: number}) do
{:ok, body} ->
Map.get(body, "valid") || false
{:error, _, _} ->
nil
end
end
defp process_response({:ok, %{body: body}}) do
process_body(body)
end
defp process_response({:error, _}) do
{:error, "There was an error with your request. Please try again."}
end
defp process_body(%{"error" => body}) do
{:error, body["code"], body["info"]}
end
defp process_body(body), do: {:ok, body}
end