open-api-spex / open_api_spex

Open API Specifications for Elixir Plug applications
Mozilla Public License 2.0
706 stars 183 forks source link

Property with type array in Schema mentioned in allOf not properly casted to struct #626

Open dkln opened 2 months ago

dkln commented 2 months ago

First of all: thanks for the hard work on this Hex package. I love it ❤️

It seems there is a small bug when casting an Object mentioned in allOf that contains a property that is an array and mentions another Schema with items.

An example. Given the following schemas:

defmodule Hobby do
  require OpenApiSpex

  alias OpenApiSpex.Schema

  OpenApiSpex.schema(%{
    type: :object,
    properties: %{
      name: %Schema{type: :string, minLength: 1, maxLength: 30}
    }
  })
end

defmodule Person do
  require OpenApiSpex

  alias OpenApiSpex.Schema

  OpenApiSpex.schema(%{
    type: :object,
    properties: %{
      hobbies: %Schema{type: :array, items: Hobby}
    }
  })
end

defmodule Employee do
  require OpenApiSpex

  alias OpenApiSpex.Schema

  OpenApiSpex.schema(%{
    type: :object,
    allOf: [
      Person,
      %Schema{
        type: :object,
        properties: %{
          employee_number: %Schema{type: :string}
        }
      }
    ]
  })
end

When using the Person schema, the casting of hobbies works as expected:

  params = %{hobbies: [%{name: "Programming"}, %{name: "Walking"}]}

  OpenApiSpex.Cast.cast("Person", params, specs)

  %Person{
    hobbies: [%Hobby{name: "Programming"}, %Hobby{name: "Walking"}]
  }

However, when using the Employee schema, the casting of hobbies doesn't work as expected (notice that hobbies now contain a list of maps instead of Hobby structs):

  params = %{hobbies: [%{name: "Programming"}, %{name: "Walking"}], employee_number: "123"}

  OpenApiSpex.Cast.cast("Employee", params, specs)

  %Employee{
    hobbies: [%{name: "Programming"}, %{name: "Walking"}],
    employee_number: "123"
  }

But, if I would change the Employee schema to:

defmodule Employee do
  require OpenApiSpex

  OpenApiSpex.schema(%{
    type: :object,
    allOf: [
      Person,
      %Schema{
        type: :object,
        properties: %{
          employee_number: %Schema{type: :string},
          hobbies: %Schema{type: :array, items: Hobby}
        }
      }
    ]
  })
end

It works:

params = %{hobbies: [%{name: "Programming"}, %{name: "Walking"}], employee_number: "123"}

OpenApiSpex.Cast.cast("Employee", params, specs)

%Employee{
  hobbies: [%Hobby{name: "Programming"}, %Hobby{name: "Walking"}],
  employee_number: "123"
}

So it seems that using allOf doesn't comply to the mentioned items schema. Hope these examples clarify the problem a bit. If you need any help or more information, please let me know! I am happy to help you out.