1player

1player

A design pattern for more flexible context APIs

A question I had when first learning contexts and Ecto was how to expand the default context API to support more flexible queries. Usually your auto-generated context modules look like:

defmodule App.Accounts do
  def list_users()
  def get_user(id)
  def get_user!(id)

  ...
end

Which soon becomes a little restrictive when you need to query your database with different filters. How do I find a user by email? How do I list only admin users? So one would create helper functions such as:

defmodule App.Accounts do
  def list_users()
  def list_admin_users()
  def get_user(id)
  def get_user!(id)
  def get_user_by_email(email)
  def get_user_by_email!(email)

  ...
end

As you can imagine, creating a function for each possible query type doesn’t scale very well, and if you introduce GraphQL to your application, where queries tend to be both user-generated and composable (find a user by email which is an admin), this way of organising your context API gets problematic.

Thankfully, the dataloader library, which is often used in conjuction with (Absinthe) GraphQL, shows an interesting pattern that can be used in all cases, not only in the GraphQL context.

dataloader mandates the creation of a query/2 function, that takes a queryable (i.e. an Ecto schema or a query) and a list of filters we want to apply to that queryable. Basically we want to take a list of filters, and build a query out of it.

def query(User, opts \\ [])
  # apply filters listed in opts and return an Ecto query
end

We can use this function to make all our context functions accept a list of filters than can be composed together:

defmodule App.Accounts do
  def query(User = queryable, opts \\ []) do
    Enum.reduce(queryable, opts, fn 
      {:email, email}, query -> 
        where(query, [u], u.email == ^email)

      {:admin?, admin?}, query -> 
        where(query, [u], u.admin? == ^admin?)

      {:in_group, group_name}, query -> 
        query
        |> join(:inner, [u], g in assoc(u, :group))
        |> where(g.name == ^group_name)
    end)
  end)

  def list_users(opts \\ []) do
    User
    |> query(opts)
    |> Repo.all()
  end

  def get_user(opts \\ []) do
    User
    |> query(opts)
    |> Repo.one()

  ...
end

All the possible filters are now encapsulated in this query function, they’re composable because Ecto is awesome, and our context API remains slim and neat. Want to find an admin user by email? Accounts.get_user(email: "foo@example.com", admin?: true). And bonus point, your context module is ready to be integrated with your GraphQL server.

An astute reader might notice that some of the filters tend to be very similar: we often want to filter a field by value (i.e. field == something), we often want to give our context API a way of ordering the results or limiting the number of rows returned. It would be nice to generalise some of these filters in a shared module. What I tend to do in my code is change the query function like this:

  def query(User = queryable, opts \\ []) do
    Enum.reduce(queryable, opts, fn 
      {:in_group, group_name}, query -> 
        query
        |> join(:inner, [u], g in assoc(u, :group))
        |> where(g.name == ^group_name)

      filter, query -> Helpers.default_query_filters(filter, query)
    end)
  end)

# in some other helper module...

def default_query_filters({:preload, preloads}, query) do
  preload(query, ^preloads)
end

def default_query_filters({:limit, n}, query) do
  limit(query, [q], ^n)
end

def default_query_filters({field, value}, query) when is_atom(field) do
  where(query, [q], field(q, ^field) == ^value)
end

The query function in the context now only contains filters and queries specific to the module, whereas the common functionality such as preloading or filtering a field by value are held by a helper module, since the logic is always the same no matter the queryable. And all this work lets us express complex queries very simply: Accounts.list_users(in_group: "Friends", admin?: true, preload: :group)

I’ve never seen this pattern in the wild, and I’ve been using it for a year at work with great success. I hope this helps somebody, and if someone has more free time than me, I imagine the default_query_filters function could be implemented in a library available for everybody to use.

Most Liked

baldwindavid

baldwindavid

This is similar to what my token_operator (GitHub - baldwindavid/token_operator: Helper to make clean keyword APIs to Phoenix context functions) package does though a bit more opinionated and probably easier to understand.

It is for this reason that I’ve mostly moved away from using the pattern in the controller in favor of explicit function references.

# controller
Calendar.list_reservations([
  &Calendar.filter_reservations_by_room(&1, rooms),
  &Calendar.filter_reservations_by_day(&1, datetime),
  &Calendar.preload_reservation_owner_and_company/1,
  &Calendar.preload_reservation_room_and_location/1
])

In the context, I just run each of those functions in succession.

# context
def list_reservations(queries \\ []) do
  Reservation
  |> (fn query -> Enum.reduce(queries, query, & &1.(&2)) end).()
  |> Repo.all()
end

Okay, really I wrap that ugly reduce part in a utility, but you get the idea.

baldwindavid

baldwindavid

I haven’t actually had the need for that, but assume will at some point. If you’re talking about doing it with the pattern using explicit function references, perhaps something like:

# controller
Syndication.list_feeds([
  &Syndication.filter_and_sort_feeds_by(&1, params)
])
# context
def filter_and_sort_feeds_by(query, attrs \\ %{}) do
  attrs
  |> Map.take(["type", "occurred_at", "resource_type", "sort_by"])
  |> Enum.map(fn {key, value} ->
    case key do
      "type" -> &filter_feeds_by_type(&1, value)
      "occurred_at" -> &filter_feeds_by_occurred_at(&1, value)
      "resource_type" -> &filter_feeds_by_resource_type(&1, value)
      "sort_by" -> &order_feeds_by(&1, value)
    end
  end)
  |> Enum.reduce(query, & &1.(&2))
end

That provides the ability to use it just like the other filters. For something that custom though, maybe simpler to just have a dedicated function that actually hits the repo.

# controller
Syndication.filter_and_sort_feeds(params)
# context
def filter_and_sort_feeds(attrs \\ %{}) do
  attrs
  |> Map.take(["type", "occurred_at", "resource_type", "sort_by"])
  |> Enum.map(fn {key, value} ->
    case key do
      "type" -> &filter_feeds_by_type(&1, value)
      "occurred_at" -> &filter_feeds_by_occurred_at(&1, value)
      "resource_type" -> &filter_feeds_by_resource_type(&1, value)
      "sort_by" -> &order_feeds_by(&1, value)
    end
  end)
  |> Enum.reduce(Feed, & &1.(&2))
  |> Repo.all()
end
OvermindDL1

OvermindDL1

This is how I’ve been programming my big project to access an old DB with lots and lots of joins to do even trivial lookups. ^.^;

I haven’t really generalized any of the lookups as if it’s simple like that I’ll just do it on-site instead, the actual ‘query’ function holds anything that’s not generic.

sb8244

sb8244

Author of Real-Time Phoenix

I use a similar pattern where I base my queries on this ListQuery implementation (https://github.com/SalesLoft/okr-app/blob/master/lib/okr_app/query/list_query.ex)

This lets me turn a map of filters into an Ecto.Query really easily, which I often use for something like def all(params). I will often write context functions that are more specific and produce the map for you, like all_for_user may take a User and create the right params for the query.

There is a downside to this approach, which is that it can be difficult to answer the question “What queries, exactly, will my system produce?” This question is important when considering indices, or if deprecating some function.

1player

1player

It makes sure to accept only the User module as first argument, and all Ecto.Schema modules are queryable.

Why does it pattern match on that schema? Because a context might be working with more than one queryable. The context shown in the example is called App.Accounts so it’s not unreasonable to have:

def query(User = queryable, opts)
  # User own queries
end

def query(Group = queryable, opts)
  # Group own queries
end

def list_users(opts \\ []), do: Repo.all(query(User, opts))
def list_groups(opts \\ []), do: Repo.all(query(Group, opts))

Where Next?

Popular in Guides/Tuts Top

pel_daniel
Hi! I created some animations to explain what happens internally with map & reduce functions. The code is open source. Any feedback...
New
New
njwest
Greetings: I just wrote a step-by-step guide on building a Phoenix 1.3 JWT Auth API with Guardian JWTs and Comeonin password hashing. I ...
New
OndrejValenta
Me and my boys started a new website specifically designed for other ASP.NET programmers that struggle, as we do, with their transformati...
New
smpallen99
Did you know that IO.inspect/2 returns the the first argument and accepts a label option as a second argument. This makes it a perfect to...
New
rhcarvalho
After collecting information from multiple sources (this forum, blogs, StackOverflow and GitHub), I was finally able to successfully embe...
New
dgamidov
Hi folks, Just a short instruction. Maybe it will help somebody. https://v4-alpha.getbootstrap.com/getting-started Install boostrap...
New
danschultzer
I wrote this blog post based on our experiences setting up continuous delivery for our first production umbrella Phoenix app. Coming from...
New
dmitriid
This is not a question, but a post for anyone who may need it in the future. Sometimes some browsers may mangle the filename if it’s non-...
New
tonydang
I recently got inertia-phoenix (an Inertia.js adapter for Phoenix) working with Svelte. Setting up the server-side rendering (SSR) with S...
New

Other popular topics Top

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
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New

We're in Beta

About us Mission Statement