Problems with router helper functions in library

Hello everyone!

I am developing a library to manage resources in an application. The User may use a macro from my library in order to generate several live views for example to show or edit a resource.

# pseudo code in router

my_macro("/path", LiveView)

# which will eventually generate
live "/path", LiveView, :index
live "/path", LiveView, :edit

In my library I defined a function to call the router helper functions in the application using my library.

So I could link to an user edit page by calling Routes.user_path(Endpoint, :edit, resource). This works fine until the user adds additional params to the path when using my macro.

For example the user maybe wants to define

my_macro("/:param/path", LiveView)

The generated router helpers functions do not work anymore, because I have to pass additional params to it: Routes.user_path(Endpoint, :edit, **param**, resource)

I came up with several solutions, but they are all kind of hacky.

Solution 1:
Somehow get the base url (the url without query params) and construct the paths manually without calling the router helper functions.

Solution 2:
Pass the path params to the router helper function. First, I have to get the path params, then I need to add them to the helper function calls dynamically.

This solution requires to get the path params only. Is there a way to get them easily? params in handle_params is a map that contains path and query params. How would you distinguish between them?

I wish there would be a helper function which takes the query and path params as an argument to generate a path.

Routes.user_path(Endpoint, :index, %{order_by: :asc, id: "xyz"}) => /xyz/user?order_by=asc
# instead of
Routes.user_path(Endpoint, :index, "xyz, "%{order_by: :asc}) => /xyz/user?order_by=asc

I know this would cause other problems, but would be the perfect solution for my problem.

I would love to hear about other ideas and solutions from you!

For your own (library) code I suggest using conn.script_name to figure out the prefix of where your stuff is mounted and go from there. Router helpers are unlikely to be a good fit for your library to route to its internal routes.

1 Like