How to use the query functions generated by code_interface?

The documentation doesn’t show how to use the query functions generated by code_interface do, and I can’t figure out how to use them, even with something simple, like this:

  code_interface do
    define_for GF.Ash.Api

    define :get_by_id, action: :read, get?: true, args: [:id]
  end

Calling the generated function like this:

iex> token = Token.get_by_id!("b18485e8-2a8e-41a5-bbe7-8729e6296f9a", authorize?: false)

** (Ash.Error.Invalid) Input Invalid

* expected at most one result but got at least 2.
      
      Please ensure your action is configured with an appropriate filter to ensure a single result is returned.
    (ash 2.17.4) lib/ash/api/api.ex:2324: Ash.Api.unwrap_or_raise!/3
    (groupflow 0.1.1) deps/ash/lib/ash/code_interface.ex:515: GF.Auth.Token.get_by_id!/3
    iex:16: (file)

It seems to ignore the id parameter I pass to it, and it tries to query all records.

So with that set up, it’s expecting the action you call to do something with the :id argument. get?: true says “with the arguments given to the action, it will only return one record”. So using get?: true, you’d need an action like this:

read :get_by_id do
  argument :id, :uuid, allow_nil?: false
  filter expr(id == ^arg(:id))
end

However, there is a short hand to allow you to pass a filter on to the action instead of having to define a custom action:

define :get_by_id, action: :read, get_by: [:id]
2 Likes

Oh nice, that works!