jearbear

jearbear

I find that much of what’s written about using Contexts focuses on abstracting away Ecto Repo operations, but will still end up returning Ecto schemas as results, leaking them into the web layer. In a personal web app I’m working on, I’ve found it helpful to enforce that this doesn’t happen by using embedded schemas at the boundaries of contexts.

I’ve landed on an approach where I will model each context as a RESTful API resource with an embedded schema describing its shape. Each context implements a Resource behavior that requires callbacks to specify the base query, query filters, and handlers for CRUD operations.

I’d love for others to chime in with how they approach this problem, or if they see it as a problem at all.

Here’s a simplified example of a resource in my app to illustrate what I’m talking about. Being declarative in this way has been helpful for me as resources get more complicated. For example, I find that extending a resource often just requires minimally updating a base_query and map_query_result.

defmodule App.Account do
  use Ecto.Schema

  use App.Resource,
    schema: App.Schemas.Account

  import Ecto.Query
  import Ecto.Changeset

  alias __MODULE__
  alias App.Repo
  alias App.Schemas

  embedded_schema do
    field :name, :string
    field :is_active, :boolean, default: true
    field :current_balance, Money.Ecto.Amount.Type
    field :available_balance, Money.Ecto.Amount.Type
  end

  @impl true
  def base_query() do
    from a in Schemas.Account,
      left_join: b in assoc(a, :balance),
      preload: [balance: b],
      order_by: :name
  end

  @impl true
  def map_query_result(result) do
    %Account{
      id: result.id,
      name: result.name,
      is_active: result.is_active,
      current_balance: result.balance.current,
      available_balance: result.balance.available,
    }
  end

  @impl true
  def handle_query_params(args, q) do
    case args do
      {_, nil} -> q
      {:id, val} -> where(q, id: ^val)
      {:name, val} -> where(q, name: ^val)
      {:is_active, val} -> where(q, is_active: ^val)
    end
  end

  @impl true
  def handle_change(account, params, _action) do
    account
    |> cast(params, [:name, :is_active])
    |> validate_required([:name])
  end
  
  @impl true
  def handle_create(params, changeset) do
    # You can put custom logic here to transform the params before
    # it's passed to the default handler, which will just update
    # the backing schema. You can omit this callback altogether to
    # use the default functionality.
    super(params, changeset)
  end

  @impl true
  def handle_update(id, params, changeset) do
    # Same as above here
    super(id, params, changeset)
  end
end

And with a use macro, the resource could be used like this:

Account.list(name: ..., is_active: ...)
Account.get(name: ...)
Account.exists?(...)

# returns the new account if valid, a changeset with errors otherwise
Account.create(%{...})

# returns the new account if valid, a changeset with errors otherwise
Account.update(account, %{...})

# useful for forms to preview validations
Account.changeset(account)

It’s definitely not as powerful as Ecto, but I find that this is kind of the point. By hiding the expressivity and power of Ecto behind a structured interface, I’m better able to focus on designing robust, reusable entities for the web layer. My setup has a few holes and limiting assumptions (such as assuming that resources have an id primary key), but hopefully you get the idea :slight_smile:

Showing Posts 1 to 2

krasenyp

krasenyp

I approach it a little bit different. I decouple the database from the business logic. The persistence layer is used like a library which the core business logic layer depends on. You pass it core data structures and it persists them. It doesn’t return Ecto structs but can return errors if the situation requires it.

jearbear

jearbear OP

That honestly doesn’t seem too far from my approach. My approach presumes that the core resources are in some way backed by a database, but I could imagine that it could be implemented to not be the case. Some resources in my app look very different than their Ecto schema and updates aren’t just simple 1-1 updates to the underlying schema. For example, I have a Merchant resource (all Transactions reference a Merchant), and when the Merchant is renamed to one that already exists, it will re-write all its Transactions to point to the new Merchant and delete itself, rather than just throwing a unique constraint violation error:

defmodule App.Merchant do
  ...

  @impl true
  def handle_create(%{name: name}, changeset) do
    # This callback needs to just return the ID of the underlying schema
    # and it will take care of returning a resource with the populated fields
    existing_merchant =
      Schemas.Merchant
      |> where(name: ^name)
      |> Repo.one()

    case existing_merchant do
      %Schemas.Merchant{id: id} ->
        {:ok, id}

      nil ->
        super(%{name: name}, changeset)
    end
  end

  @impl true
  def handle_update(id, %{name: new_name}, changeset) do
    # Same as above here
    existing_merchant =
      Schemas.Merchant
      |> where([m], m.id != ^id and m.name == ^new_name)
      |> Repo.one()

    case existing_merchant do
      %Schemas.Merchant{id: new_id} ->
        Schemas.Transaction
        |> where(merchant_id: ^id)
        |> Repo.update_all(set: [merchant_id: new_id])

        Repo.delete!(%Schemas.Merchant{id: id})

        {:ok, new_id}

      nil ->
        super(id, %{name: new_name}, changeset)
    end

  ...
  end
— All posts loaded —

Where Next? Top

Trending in Discussions Top

cblavier
Hey there, It’s been more than a year since we started using LiveView as our main UI library and building a whole library of UI componen...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
axelson
Hi there! :wave: @frigidcode and I (but mostly him) have been running an Elixir Book club, we’re almost done with Designing Elixir Syste...
New
achempion
I’ve been using Emacs as my main code editor for more than a two years. It’s a custom build version although I’ve tried doom emacs and sp...
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New
jtormey
Lately I’ve been thinking about how to organize components as a LiveView application grows. One of the pain points I’ve found (for myself...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
georgeguimaraes
Just published claude-code-elixir, a plugin marketplace for Claude Code with Elixir support. These are the plugins I’ve been using for my...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews