View Source OpenApiSpex.Cast (open_api_spex v3.16.0)

Cast and validate a value against an OpenApiSpex schema

Link to this section Summary

Link to this section Types

@type cast_opt() :: {:apply_defaults, boolean()}
@type read_write_scope() :: nil | :read | :write
@type schema_or_reference() :: OpenApiSpex.Schema.t() | OpenApiSpex.Reference.t()
@type t() :: %OpenApiSpex.Cast{
  errors: [OpenApiSpex.Cast.Error.t()],
  index: integer(),
  key: atom() | nil,
  opts: [cast_opt()],
  path: [atom() | String.t() | integer()],
  read_write_scope: read_write_scope(),
  schema: schema_or_reference() | nil,
  schemas: map(),
  value: term()
}

Link to this section Functions

@spec cast(t()) :: {:ok, term()} | {:error, [OpenApiSpex.Cast.Error.t()]}
Link to this function

cast(schema, value, schemas \\ %{}, opts \\ [])

View Source
@spec cast(schema_or_reference() | nil, term(), map(), [cast_opt()]) ::
  {:ok, term()} | {:error, [OpenApiSpex.Cast.Error.t()]}

Cast and validate a value against the given schema.

Recognizes all the types defined in Open API (itself a superset of JSON Schema).

JSON Schema types: https://json-schema.org/latest/json-schema-core.html#rfc.section.4.2.1

Open API primitive types: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types

For an :object schema type, the cast operation returns a map with atom keys.

examples

Examples

iex> alias OpenApiSpex.{Cast, Schema}
iex> schema = %Schema{type: :string}
iex> Cast.cast(schema, "a string")
{:ok, "a string"}
iex> Cast.cast(schema, 1..100)
{
  :error,
  [
    %OpenApiSpex.Cast.Error{
      reason: :invalid_type,
      type: :string,
      value: 1..100
    }
  ]
}
iex> schema = %Schema{
...>    type: :object,
...>    properties: %{
...>      name: nil
...>    },
...>    additionalProperties: false
...> }
iex> Cast.cast(schema, %{"name" => "spex"})
{:ok, %{name: "spex"}}
iex> Cast.cast(schema, %{"bad" => "spex"})
{
  :error,
  [
    %OpenApiSpex.Cast.Error{
      name: "bad",
      path: ["bad"],
      reason: :unexpected_field,
      value: %{"bad" => "spex"}
    }
  ]
}
Link to this function

success(ctx, schema_properties)

View Source