Best Practices to compose JSON views in the new Phoenix 1.7

Hello everyone,

I am currently working on a project that uses Phoenix 1.7 and I am unsure if there are any best practices when it comes to composing views for JSON. I am relatively new to Phoenix so that any guidance would be greatly appreciated.

I am curious about how to handle nested data structures in my JSON responses. Are there any specific techniques or conventions that I should be following?

A Naive example of two JSON views that could be composed are:

defmodule MyApp.CarJSON do
  alias MyApp.Car

  def show(%{car: car}) do
    %{data: data(car)}
  end

  defp data(%Car{} = car) do
    %{
      year: car.year,
      brand: car.brand
    }
  end
end

defmodule MyApp.BrandJSON do
  alias MyApp.Brand

  def show(%{brand: brand}) do
    %{data: data(brand)}
  end

  defp data(%Brand{} = brand) do
    %{
      brand_name: brand.name
    }
  end
end

My doubt here is, how I can compose these two views in a way that I don’t break this pattern. Any advice or resources that you can provide would be incredibly helpful. Thank you in advance for your assistance.

1 Like

It is all functions, so you should be able to do BrandJSON.show(brand) from CarJSON. :slight_smile:

3 Likes

You are totally right, I thought it might have something like the old way of declaring these views where we have render_one and render_many.

After I posted here I think that the better way is to expose the data function or rename it to render which in this case makes more sense and call BrandJSON.render(brand).

1 Like