@@ -1247,19 +1247,50 @@ defmodule AshJsonApi.Serializer do
12471247 end
12481248
12491249 defp do_serialize_value ( value , type , constraints , domain , opts ) do
1250- with Ash.Type.Struct <- type ,
1251- instance_of when not is_nil ( instance_of ) <- constraints [ :instance_of ] ,
1252- true <- Ash.Resource.Info . resource? ( instance_of ) do
1253- req = % { fields: % { } , route: % { } , domain: domain }
1254- serialize_attributes ( req , value , opts )
1255- else
1256- _ ->
1257- if Ash.Resource.Info . resource? ( type ) do
1258- req = % { fields: % { } , route: % { } , domain: domain }
1259- serialize_attributes ( req , value , opts )
1260- else
1261- value
1262- end
1250+ cond do
1251+ type == Ash.Type.Struct and not is_nil ( constraints [ :instance_of ] ) and
1252+ Ash.Resource.Info . resource? ( constraints [ :instance_of ] ) ->
1253+ req = % { fields: % { } , route: % { } , domain: domain }
1254+ serialize_attributes ( req , value , opts )
1255+
1256+ type in [ Ash.Type.Struct , Ash.Type.Map ] and is_list ( constraints [ :fields ] ) and
1257+ is_map ( value ) ->
1258+ serialize_constrained_fields ( value , constraints [ :fields ] , domain , opts )
1259+
1260+ Ash.Resource.Info . resource? ( type ) ->
1261+ req = % { fields: % { } , route: % { } , domain: domain }
1262+ serialize_attributes ( req , value , opts )
1263+
1264+ true ->
1265+ value
1266+ end
1267+ end
1268+
1269+ defp serialize_constrained_fields ( value , fields , domain , opts ) do
1270+ Enum . reduce ( fields , % { } , fn { name , config } , acc ->
1271+ case fetch_field_value ( value , name ) do
1272+ { :ok , field_value } ->
1273+ serialized =
1274+ serialize_value (
1275+ field_value ,
1276+ Ash.Type . get_type ( config [ :type ] ) ,
1277+ config [ :constraints ] || [ ] ,
1278+ domain ,
1279+ opts
1280+ )
1281+
1282+ Map . put ( acc , to_string ( name ) , serialized )
1283+
1284+ :error ->
1285+ acc
1286+ end
1287+ end )
1288+ end
1289+
1290+ defp fetch_field_value ( value , name ) do
1291+ case Map . fetch ( value , name ) do
1292+ { :ok , field_value } -> { :ok , field_value }
1293+ :error -> Map . fetch ( value , to_string ( name ) )
12631294 end
12641295 end
12651296
0 commit comments