Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New docs for json views in Phoenix #341

Open
snewcomer opened this issue Oct 14, 2024 · 1 comment
Open

New docs for json views in Phoenix #341

snewcomer opened this issue Oct 14, 2024 · 1 comment

Comments

@snewcomer
Copy link
Contributor

Do we need new docs? Sry its been a while since I've looked at Phoenix, but with this new paradigm, it seems like we would make use of the Serializer?

https://hexdocs.pm/phoenix/json_and_apis.html

The usage docs

defmodule MyApp.PostView do
  use JSONAPI.View, type: "posts"

  def fields do
    [:text, :body, :excerpt]
  end

The default blueprint json file generated from mix.

defmodule MyApp.PostJSON do
  @doc """
  Renders a list of posts.
  """
  def index(%{posts: posts}) do
    %{data: for(post <- posts, do: data(post))}
  end

  @doc """
  Renders a single post.
  """
  def show(%{post: post}) do
    %{data: data(post)}
  end

  defp data(%Post{} = post) do
    %{
      id: post,
      text: post.text
    }
  end
end
@snewcomer snewcomer changed the title New docs for New docs for json views in Phoenix Oct 16, 2024
@snewcomer
Copy link
Contributor Author

To support a view that also supports JSONAPI, we need to create a separate object_json_api.ex that serializes the data passed from the controller and puts the appropriate view based on the headers.

Something like this so that render dispatches to the appropriate json serialization module.

  def get_request_format(conn) do
    case get_req_header(conn, "content-type") do
      ["application/vnd.api+json" | _] -> "json-api"
      _ -> "json"
    end
  end

.....

def put_format_view(conn) do
  case get_request_format(conn) do
      "json-api" ->
        conn
        |> put_resp_content_type("application/vnd.api+json")
        |> put_view(module.json_api_view())
      _ ->
        conn
        |> put_resp_content_type("application/json")
        |> put_view(module.json_view())
    end
end
|> render(:show, object: object)

Here is the docs for render.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant