forma v0.4.0 Forma View Source

Applies typespecs to JSON-like data.

This module can parse JSON-like data (such as maps with key strings) into a more structured form by trying to map it to conform to a module’s typespec.

This can generally be useful when interfacing with external data sources that provide you data as JSON or MessagePack, but that you wish to transform into either proper structs or richer data types without a native JSON representation (such as dates or sets) in your application.

It is heavily inspired by Go’s way of dealing with JSON data.

defmodule User do
  defstruct [:id, :name, :age, :gender]

  @type t :: %__MODULE__{
    id: String.t,
    name: String.t,
    age: non_neg_integer(),
    gender: :male | :female | :other | :prefer_not_to_say
  }
end

Forma.parse(%{"id" => "1", "name" => "Fredrik", "age" => 30, "gender" => "male"}, User)
# => %User{id: "1", name: "Fredrik", age: 30, gender: :male}

Forma tries to figure out how to translate its input to a typespec. However, not all types have natural representations in JSON, for example dates, or don’t want to expose their internals (opaque types).

If you’re in control of the module defining the type, you can implement the __forma__/2 function to handle parsing input to your desired type

defmodule App.Date do
  @opaque t :: Date

  # first argument is the type to be parsed in this module
  def __forma__(:t, input) do
    case Date.from_iso8601(input) do
      {:ok, date} -> date
      {:error, reason} -> raise reason
    end
  end
end

If you’re not in control of the module, you can pass a parser along as an optional argument,

defmodule LogRow do
  defstruct [:log, :timestamp]

  type t :: %__MODULE__{
    log: String.t,
    timestamp: NaiveDateTime.t
  }
end

Forma.parse(%{"log" => "An error occurred", "timestamp" => "2015-01-23 23:50:07"},
  %{{NaiveDateTime, :t} => fn input ->
    case NaiveDateTime.from_iso8601(input) do
      {:ok, datetime} -> datetime
      {:error, err} -> raise err
    end
  end})

The number of arguments to the parser functions depends on if the type is parameterized or not (MapSet.t vs MapSet.t(integer)).

Link to this section Summary

Functions

Called when an application is started

Link to this section Types

Link to this type callback() View Source
callback() :: (input(), [] -> any())
Link to this type input() View Source
input() ::
  %{optional(String.t()) => any()} |
  [any()] |
  String.t() |
  number()
Link to this type parsers() View Source
parsers() :: %{optional(typeref()) => callback()}
Link to this type typeref() View Source
typeref() :: {atom(), atom()}

Link to this section Functions

Link to this function parse(input, module, parsers \\ %{}) View Source
parse(input(), typeref(), parsers()) :: any()
parse(input(), atom(), parsers()) :: any()

Called when an application is started.

This function is called when an application is started using Application.start/2 (and functions on top of that, such as Application.ensure_started/2). This function should start the top-level process of the application (which should be the top supervisor of the application’s supervision tree if the application follows the OTP design principles around supervision).

start_type defines how the application is started:

  • :normal - used if the startup is a normal startup or if the application is distributed and is started on the current node because of a failover from another node and the application specification key :start_phases is :undefined.
  • {:takeover, node} - used if the application is distributed and is started on the current node because of a failover on the node node.
  • {:failover, node} - used if the application is distributed and is started on the current node because of a failover on node node, and the application specification key :start_phases is not :undefined.

start_args are the arguments passed to the application in the :mod specification key (e.g., mod: {MyApp, [:my_args]}).

This function should either return {:ok, pid} or {:ok, pid, state} if startup is successful. pid should be the PID of the top supervisor. state can be an arbitrary term, and if omitted will default to []; if the application is later stopped, state is passed to the stop/1 callback (see the documentation for the c:stop/1 callback for more information).

use Application provides no default implementation for the start/2 callback.

Callback implementation for Application.start/2.