Skip to content

Commit

Permalink
fix: encode primary key always when encoding resources as values
Browse files Browse the repository at this point in the history
fixes #263
  • Loading branch information
zachdaniel committed Dec 3, 2024
1 parent 652275a commit d87f4c2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
2 changes: 1 addition & 1 deletion lib/ash_json_api/json_schema/open_api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -923,7 +923,7 @@ if Code.ensure_loaded?(OpenApiSpex) do

@spec resource_relationship_field_data(
resource :: module,
Relationship.t()
relationship :: Ash.Resource.Relationships.relationship()
) :: Schema.t()
defp resource_relationship_field_data(_resource, %{
cardinality: :many,
Expand Down
18 changes: 10 additions & 8 deletions lib/ash_json_api/serializer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -664,13 +664,14 @@ defmodule AshJsonApi.Serializer do
end
end

defp serialize_attributes(_, nil), do: nil
defp serialize_attributes(request, records, opts \\ [])
defp serialize_attributes(_, nil, _opts), do: nil

defp serialize_attributes(request, records) when is_list(records) do
Enum.map(records, &serialize_attributes(request, &1))
defp serialize_attributes(request, records, opts) when is_list(records) do
Enum.map(records, &serialize_attributes(request, &1, opts))
end

defp serialize_attributes(request, %resource{} = record) do
defp serialize_attributes(request, %resource{} = record, opts) do
fields =
Map.get(request.fields, resource) || Map.get(request.route, :default_fields) ||
default_attributes(resource)
Expand Down Expand Up @@ -703,7 +704,8 @@ defmodule AshJsonApi.Serializer do
end

cond do
AshJsonApi.Resource.only_primary_key?(resource, field_name) ->
AshJsonApi.Resource.only_primary_key?(resource, field_name) &&
Keyword.get(opts, :skip_only_primary_key?, true) ->
acc

!field ->
Expand Down Expand Up @@ -743,12 +745,12 @@ defmodule AshJsonApi.Serializer do
instance_of when not is_nil(instance_of) <- constraints[:instance_of],
true <- Ash.Resource.Info.resource?(instance_of) do
req = %{fields: %{}, route: %{}, domain: domain}
serialize_attributes(req, value)
serialize_attributes(req, value, skip_only_primary_key?: false)
else
_ ->
if Ash.Type.embedded_type?(type) do
if Ash.Resource.Info.resource?(type) do
req = %{fields: %{}, route: %{}, domain: domain}
serialize_attributes(req, value)
serialize_attributes(req, value, skip_only_primary_key?: false)
else
value
end
Expand Down

0 comments on commit d87f4c2

Please sign in to comment.