Skip to content

Commit

Permalink
Allow the SendGrid API key to be set in the ENV (#342)
Browse files Browse the repository at this point in the history
This change allows the SendGrid API key to be set via environment
variables at runtime.
  • Loading branch information
dazoakley authored and paulcsmith committed Jan 30, 2018
1 parent 9783c19 commit ec9b79c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
21 changes: 12 additions & 9 deletions lib/bamboo/adapters/send_grid_adapter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ defmodule Bamboo.SendGridAdapter do
# In config/config.exs, or config.prod.exs, etc.
config :my_app, MyApp.Mailer,
adapter: Bamboo.SendGridAdapter,
api_key: "my_api_key"
api_key: "my_api_key" # or {:system, "SENDGRID_API_KEY"}
# Define a Mailer. Maybe in lib/my_app/mailer.ex
defmodule MyApp.Mailer do
Expand Down Expand Up @@ -49,20 +49,23 @@ defmodule Bamboo.SendGridAdapter do

@doc false
def handle_config(config) do
if config[:api_key] in [nil, ""] do
raise_api_key_error(config)
else
config
end
# build the api key - will raise if there are errors
Map.merge(config, %{api_key: get_key(config)})
end

@doc false
def supports_attachments?, do: true

defp get_key(config) do
case Map.get(config, :api_key) do
nil -> raise_api_key_error(config)
key -> key
api_key = case Map.get(config, :api_key) do
{:system, var} -> System.get_env(var)
key -> key
end

if api_key in [nil, ""] do
raise_api_key_error(config)
else
api_key
end
end

Expand Down
21 changes: 21 additions & 0 deletions test/lib/bamboo/adapters/send_grid_adapter_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ defmodule Bamboo.SendGridAdapterTest do

@config %{adapter: SendGridAdapter, api_key: "123_abc"}
@config_with_bad_key %{adapter: SendGridAdapter, api_key: nil}
@config_with_env_var_key %{adapter: SendGridAdapter, api_key: {:system, "SENDGRID_API"}}

defmodule FakeSendgrid do
use Plug.Router
Expand Down Expand Up @@ -69,6 +70,26 @@ defmodule Bamboo.SendGridAdapterTest do
end
end

test "can read the api key from an ENV var" do
System.put_env("SENDGRID_API", "123_abc")

config = SendGridAdapter.handle_config(@config_with_env_var_key)

assert config[:api_key] == "123_abc"
end

test "raises if an invalid ENV var is used for the API key" do
System.delete_env("SENDGRID_API")

assert_raise ArgumentError, ~r/no API key set/, fn ->
new_email(from: "foo@bar.com") |> SendGridAdapter.deliver(@config_with_env_var_key)
end

assert_raise ArgumentError, ~r/no API key set/, fn ->
SendGridAdapter.handle_config(@config_with_env_var_key)
end
end

test "deliver/2 sends the to the right url" do
new_email() |> SendGridAdapter.deliver(@config)

Expand Down

0 comments on commit ec9b79c

Please sign in to comment.