Skip to content

Instantly share code, notes, and snippets.

@renanlage
Created April 1, 2019 14:09
Show Gist options
  • Save renanlage/560a376358175645f6c35125e47924e8 to your computer and use it in GitHub Desktop.
Save renanlage/560a376358175645f6c35125e47924e8 to your computer and use it in GitHub Desktop.
defmodule Notificator do
def notify(topic, %{account_id: account_id} = event) do
# Do some stuff with account_id
resource_identifier = resource_for_topic(topic, event)
with {:ok, resorce_data} = Transfers.get_resource(resource_identifier),
{:ok, notification_params} <-
to_notification(topic, event, resource_identifier, resource_data),
{:ok, notification} <- Notification.save(notification_params) do
Client.notify(notification)
end
end
defp to_notification(topic, event, resource_identifier, resource_data) do
%{
timestamp: format_datetime(event["timestamp"]),
webhook_sent_at: format_datetime(NaiveDateTime.utc_now()),
env: get_env(),
type: type_for_topic(topic),
resource_data: resource_data
}
|> Map.merge(resource_identifier)
end
defp type_for_topic("domain.inbound_external_transfer.received"),
do: "cash_in_external_transfer_transfer"
defp type_for_topic("domain.internal_transfer.received"), do: "cash_in_internal_transfer"
defp resource_for_topic("domain.inbound_external_transfer.received", %{
"statement_entry_id" => resource_id
}),
do: %{resource_type: "statement_entries", resource_id: resource_id}
defp resource_for_topic("domain.outbound_external_transfer.refunded", %{
"transfer_id" => resource_id
}),
do: %{resource_type: "external_transfers", resource_id: resource_id}
defp resource_for_topic(_), do: raise("unsupported topic")
defp format_datetime(datetime) when is_binary(datetime) do
datetime
|> NaiveDateTime.from_iso8601!()
|> format_datetime()
end
defp format_datetime(datetime) do
datetime
|> NaiveDateTime.truncate(:second)
|> DateTime.from_naive!("Etc/UTC")
|> DateTime.to_iso8601()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment