beam-community / jsonapi

JSON:API Serializer and Query Handler for Elixir
https://hex.pm/packages/jsonapi
MIT License
497 stars 78 forks source link

Query Parser infer view #345

Open ghbutton opened 4 days ago

ghbutton commented 4 days ago

Do you think it would be possible to use the QueryParser without specifying the view? The view is inferred (I think) if you dont use the QueryParser.

This is a code snippet that I thought we could try for:

defmodule Web.PostController do
  plug JSONAPI.QueryParser
...
end

I am happy to try to write the code if this makes sense

mattpolzin commented 4 days ago

The QueryParser uses the view to determine which includes and field names are valid and will produce an error for any other values the request specifies. That means a usage like you are suggesting would expressly disallow includes or sparse field sets if I am understanding you correctly.

That said, it doesn't seem unreasonable to me to desire to use the query parser on its own without a view given that you can also explicitly list allowed includes (although not fields). Still, it would be a pretty unusual desire I would think. Have you considered specifying a "null view" for your use-case? Just any old view you want to define with no attributes or relationships on it that you can use to satisfy the view needed by the plug currently.

ghbutton commented 3 days ago

Given this contrived example:

Controller:

defmodule App.Api.PostController do
  use RichWeb, :controller

  alias App.Repo
  alias App.Post

  def index(conn, _params) do
    posts = Repo.all(Post)

    render(conn, :index, data: post)
  end
end

View:

defmodule App.Api.PostJSON do
  use JSONAPI.View, type: "posts"

  def fields do
    [:title, :body]
  end
end

I dont need to specify a view in the controller because the phoenix controller already knows which view to use (I think). I was wondering if the QueryParser could infer the view similarly? I am not a phoenix / elixir expert so I dont know how this is done but perhaps I could find out.

mattpolzin commented 3 days ago

I see, it’s not that you want the query parser to operate without knowledge of the view, it’s that you want the query parser not to need to take the view explicitly.

ghbutton commented 3 days ago

Yes, sorry if I worded that poorly.

ghbutton commented 3 days ago

It would reduce the boiler plate I have to write.