ash-project / ash_json_api

The JSON:API extension for the Ash Framework
https://hexdocs.pm/ash_json_api
MIT License
55 stars 41 forks source link

Better error messages when accessing `related` route for a private relationship #169

Closed sevenseacat closed 1 month ago

sevenseacat commented 1 month ago

Describe the bug

Similar to #166 but occurs for related routes, not includes.

When attempting to access the related route for a relationship that is not marked public? true, a confusing error message is returned.

To Reproduce

The resource:

Tunez.Music.Artist:

  json_api do
    type "artist"

    routes do
      base "/artists"
      related :albums, :read
    end
  end

  relationships do
    has_many :albums, Tunez.Music.Album do
      # public? true
    end
  end

The request:

http://localhost:4000/api/artists/4fad50ae-9f07-49c1-a04a-560477a5d47d/albums

The error:

[error] ** (KeyError) key :destination not found in: nil

If you are using the dot syntax, such as map.field, make sure the left-hand side of the dot is a map
    (ash_json_api 1.2.0) lib/ash_json_api/controllers/get_related.ex:16: AshJsonApi.Controllers.GetRelated.call/2
    (tunez 0.1.0) deps/plug/lib/plug/router.ex:246: anonymous fn/4 in TunezWeb.JsonAPIRouter.dispatch/2
    (telemetry 1.2.1) /Users/rebecca/Projects/work/book/tunez/deps/telemetry/src/telemetry.erl:321: :telemetry.span/3
    (tunez 0.1.0) deps/plug/lib/plug/router.ex:242: TunezWeb.JsonAPIRouter.dispatch/2
    (tunez 0.1.0) lib/tunez_web/json_api_router.ex:1: TunezWeb.JsonAPIRouter.plug_builder_call/2
    (phoenix 1.7.12) lib/phoenix/router/route.ex:42: Phoenix.Router.Route.call/2
    ...

If uncommenting the public? true line on the relationship, the request works as expected.

Expected behavior

A properly formatted JSON response to the user that they've requested something invalid.

I wonder if we could also make it a compilation error for the developer - you can't request something that isn't public?

Runtime