View Source DataSpecs.Plug.Cast (dataspecs v2.1.0)

DataSpecs Plug.

NOTE: this module is available if you include the optional dependency plug.

This module can be used to plug a "Jason.decode! -> DataSpecs.cast" pipeline in your routes.

For example:

defmodule Api.Router.Something do
  use Plug.Router
  import DataSpecs.Plug.Cast, only: [typeref: 2, value: 1]

  plug :match
  plug DataSpecs.Plug.Cast
  plug :dispatch

  post "/foo", typeref(Api.Model.Foo, :t) do
    %Api.Model.Foo{...} = value(conn)
    ...
  end
end

defmodule Api.Model.Foo do
  defmodule Bar do
    @enforce_keys [:b1]
    defstruct @enforce_keys ++ [:b2]

    @type t :: %__MODULE__{
            b1: number(),
            b2: nil | String.t()
          }
  end

  @enforce_keys [:a, :bars]
  defstruct @enforce_keys

  @type t :: %__MODULE__{
          a: non_neg_integer(),
          bars: [Bar.t()]
        }
end

Summary

Functions

Callback implementation for Plug.call/2.

Callback implementation for Plug.init/1.

Declare the type the body of a route should conform

Get the casted value.

Functions

Callback implementation for Plug.call/2.

Callback implementation for Plug.init/1.

Link to this function

typeref(module, type \\ :t)

View Source
@spec typeref(module(), DataSpecs.Types.type_id()) :: [
  {:assigns, %{dataspec: %{type: DataSpecs.Types.mt(), value: term()}}}
]

Declare the type the body of a route should conform

For example:

post "/foo", typeref(Model.Foo) do
  ...
end
@spec value(Plug.Conn.t()) :: term()

Get the casted value.

For example:

post "/foo", typeref(Api.Model.Foo, :t) do
  %Api.Model.Foo{...} = value(conn)
  ...
end