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.