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

jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
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
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
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement