Skip to content

Commit

Permalink
Create Slack module
Browse files Browse the repository at this point in the history
  • Loading branch information
tteerawat committed Apr 17, 2021
1 parent 7b14453 commit 18b8473
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/satana/slack.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
defmodule Satana.Slack do
alias Satana.HTTPClient
alias Satana.Slack.Config

require Logger

@spec send_message(String.t(), String.t() | nil) :: :ok | :error
def send_message(text, webhook_url \\ nil) do
url = webhook_url || Config.new().webhook_url
body_params = %{text: text}

case HTTPClient.json_request(:post, url, body_params: body_params) do
{:ok, %HTTPClient.Response{status: 200}} ->
:ok

error ->
Logger.error(fn -> "Unable to send Slack message - #{inspect(error)}" end)

:error
end
end
end
19 changes: 19 additions & 0 deletions lib/satana/slack/config.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
defmodule Satana.Slack.Config do
@enforce_keys [:webhook_url]

defstruct @enforce_keys

@type t :: %__MODULE__{
webhook_url: String.t()
}

@spec new :: t()
def new do
key_value = Application.get_env(:satana, __MODULE__)
webhook_url = Keyword.fetch!(key_value, :webhook_url)

%__MODULE__{
webhook_url: webhook_url
}
end
end
41 changes: 41 additions & 0 deletions test/satana/slack_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
defmodule Satana.SlackTest do
use ExUnit.Case, async: true

import ExUnit.CaptureLog

alias Satana.Slack

setup do
{:ok, bypass: Bypass.open()}
end

describe "send_message/2" do
test "handles 200 status code", %{bypass: bypass} do
Bypass.expect_once(bypass, "POST", "/", fn conn ->
Plug.Conn.resp(conn, 200, "ok")
end)

text = "Hello world!"
webhook_url = "http://localhost:#{bypass.port}"

result = Slack.send_message(text, webhook_url)

assert result == :ok
end

test "handles error", %{bypass: bypass} do
Bypass.expect_once(bypass, "POST", "/", fn conn ->
Plug.Conn.resp(conn, 500, "boom")
end)

text = "Hello world!"
webhook_url = "http://localhost:#{bypass.port}"

assert capture_log(fn ->
result = Slack.send_message(text, webhook_url)

assert result == :error
end) =~ "[error] Unable to send Slack message"
end
end
end

0 comments on commit 18b8473

Please sign in to comment.