goncalotomas

goncalotomas

Cleanly separating Verified Routes using Boundary

I’m working on a Phoenix LiveView app that uses boundary, and we’ve bumped into warnings writing out a way to do notifications. There are a couple of tricks that would remove these warnings, but I care about the right way to model data and to organize the code. :slight_smile:

Here’s a rough example of the code I’m working with:

defmodule MyApp.Notifications do
  @moduledoc """
  The Notifications module is responsible for managing user notifications - both in-app and email.
  """
  use Boundary, top_level?: true
  # importing verified routes 
  use MyAppWeb, :verified_routes

  def send_invitation(invitation) do
    to =
      if invitation.user_id do
        url(~p"/app/users/invitations")
      else
        url(~p"/auth/register"))
      end

    MyApp.Mailer.deliver_invitation_email(invitation, to)
    send_invitation_notification(invitation)

    # ...
    :ok
  end

  defp send_notification(invitation) do
    # ...
  end
end

The real code is a bit more complicated, but hopefully this illustrates the issue.

We’ve configured Boundary to reject any calls to from the MyApp context to the MyAppWeb context, which makes this module not pass the boundary checks:

warning: forbidden reference to MyAppWeb
  (references from MyApp.Notifications to MyAppWeb are not allowed)
  lib/my_app/notifications.ex:17

It makes sense to prevent access to the Web context from the non-Web, but in this case we’re, were just trying to use verified routes so that the links for the invitations are verified to exist. Previously we could use Phoenix.Router.Helpers, but from the docs, it looks like the routes module helper is deprecated, so no help there.

Moving the logic that switches between the possible URLs inside the Mailer doesn’t seem helpful, since it looks like we’re leaking the logic around Invitations when Mailer should just care about sending email.

We’ve also toyed with a few ideas that basically revolve around replacing the Route Helpers module, but quickly ran into the thought of “there’s got to be a better way to do this”.

Can someone help us organize our code a bit better?

Thanks! :smiley:

Most Liked

LostKobrakai

LostKobrakai

You can move what use MyAppWeb, :verified_routes does to a separate module, which you can independently scope with boundary.

You could also reverse the dependency by injecting the module for url generation e.g. using config. Works around Boundary a bit, but imo is the architectually cleaner approach.

goncalotomas

goncalotomas

There was a new talk from Saša recently published that talks about the process of both incorporating boundary into a large new codebase and also working towards removing projects from umbrella format:

I found it a great talk, and there’s no better source than the author about this library :grin:

al2o3cr

al2o3cr

I’ve used the “module in config” approach to solve this exact issue in an umbrella app.

It has a couple components:

  • a module in MyAppWeb that exposes a URL-generation API
  • code in MyApp that looks up a module and then calls functions on it
  • config to set the key for MyApp to the module from MyAppWeb
defmodule MyAppWeb.NotificationUrls
  def for_invitation(invitation) do
    if invitation.user_id do
      url(~p"/app/users/#{invitation.user_id}/invitations")
    else
      url(~p"/auth/register")
    end
  end
end
defmodule MyApp.Notifications do
  ...
  def send_invitation(invitation) do
    to = url_module().for_invitation(invitation)

    ...
  end

  defp url_module do
    Application.fetch_env!(:my_app, :notification_urls)
  end
config :my_app, notification_urls: MyAppWeb.NotificationUrls

One downside of this simple approach is that the dynamic apply is very hard for most tools to “see through”, so you probably won’t get compile-time warnings if something’s incorrect (calling for_invitation with the wrong arity, etc)

You can mitigate most of that with some additional boilerplate-y code:

  • extract the Application.fetch_env! part and the call into a separate module in MyApp
  • create a @behaviour that it implements
  • also implement the behaviour in MyAppWeb.NotificationUrls

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29703 241
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

We're in Beta

About us Mission Statement