Ash FrameworkAF
Ash Framework4mo ago
13 replies
Shahryar

Load data works in terminal but in json api it returns empty

Inside this code i am trying to load all versions of a record for example, it works in my terminal and paper_trail_versions has some records as a list but in api json call the paper_trail_versions is [] empty
  action :list_versions_api, :struct do
      constraints instance_of: MishkaCms.Runtime.Layout
      argument :layout_id, :uuid, allow_nil?: false
      argument :layout, :map, default: %{}

      run fn input, context ->
        layout_id = input.arguments.layout_id

        not_found_error =
          {:error, Ash.Error.Query.NotFound.exception(resource: MishkaCms.Runtime.Layout)}

        layout_params =
          for {k, v} <- input.arguments.layout,
              k in ["limit", "offset"],
              into: %{},
              do: {String.to_existing_atom(k), String.to_integer(v)}

        with {:ok, layout} when not is_nil(layout) <-
               Ash.get(MishkaCms.Runtime.Layout, layout_id, action: :get_any, authorize?: false),
             :authorized <-
               if(is_nil(context.tenant) or layout.site_id == context.tenant,
                 do: :authorized,
                 else: not_found_error
               ) do
          limit = layout_params[:limit] || 20
          offset = layout_params[:offset] || 0

          # Load versions through the proper relationship
          versions_load_query =
            MishkaCms.Runtime.Layout.Version
            |> Ash.Query.sort(version_inserted_at: :desc)
            |> Ash.Query.limit(limit)
            |> Ash.Query.offset(offset)

          # Load the layout with versions
          layout
          |> Ash.load!([paper_trail_versions: versions_load_query], authorize?: false)
          |> IO.inspect(label: "Loaded Layout=====")
          |> then(&{:ok, &1})
        else
          {:error, _} = error -> error
          _ -> not_found_error
        end
      end
    end


Thank you in advance
Solution
But you'd add a calculation like sorted_versions or something
Was this page helpful?