Current section
Files
Jump to
Current section
Files
lib/hyphen/utils.ex
defmodule Hyphen.Utils do
@moduledoc false
@spec random_id() :: String.t()
def random_id do
<<a::binary-8, b::binary-8>> = :crypto.strong_rand_bytes(16)
bytes = <<
a::binary-8,
System.system_time(:microsecond)::8*8,
b::binary-8
>>
Base.url_encode64(bytes, padding: false)
end
@spec salt!(module()) :: String.t()
def salt!(endpoint) do
case endpoint.config(:hyphen) do
nil ->
raise "Missing :hyphen config for endpoint #{inspect(endpoint)}"
config ->
case Keyword.fetch(config, :signing_salt) do
{:ok, salt} ->
salt
:error ->
raise "Missing :signing_salt in :hyphen config for endpoint #{inspect(endpoint)}"
end
end
end
@spec error_message(term) :: String.t()
def error_message(error)
def error_message({:error, reason}) do
error_message(reason)
end
def error_message(errmsg) when is_binary(errmsg) do
errmsg
end
def error_message(%{__exception__: true} = e) do
Exception.message(e)
end
def error_message({%{__exception__: true} = e, stack}) when is_list(stack) do
error_message(e)
end
def error_message({:http_error, status, body}) when is_integer(status) do
"HTTP Error #{status} with #{inspect(body)}"
end
def error_message({atom, reason}) when is_atom(atom) do
to_string([Atom.to_string(atom), ": ", error_message(reason)])
end
def error_message(error) do
safe_to_string(error)
end
@doc """
Returns a string representation for the given `term`. Falls back to `inspect`
if the term does not implement `String.Chars`.
"""
@spec safe_to_string(term) :: String.t()
def safe_to_string(term) do
to_string(term)
rescue
_ -> inspect(term)
end
end