Typed_ecto_schema - A library to define Ecto schemas with typespecs without all the boilerplate code

Hey guys, I finally released the first version of my new library: typed_ecto_schema.
It is based on the amazing typed_struct lib but adapted (a lot) to fit Ecto schema definition.
It can reduce a lot the boilerplate for defining types for Ecto Schemas.

For example, if you want to add type information about your Ecto.Schema, you normally do something
like this:

defmodule Person do
  use Ecto.Schema

  @enforce_keys [:name]

  schema "people" do
    field(:name, :string)
    field(:age, :integer)
    field(:happy, :boolean, default: true)
    field(:phone, :string)
    belongs_to(:company, Company)
    timestamps(type: :naive_datetime_usec)
  end

  @type t() :: %__MODULE__{
          __meta__: Ecto.Schema.Metadata.t(),
          id: integer() | nil,
          name: String.t(),
          age: non_neg_integer() | nil,
          happy: boolean(),
          phone: String.t() | nil,
          company_id: integer() | nil,
          company: Company.t() | Ecto.Association.NotLoaded.t() | nil,
          inserted_at: NaiveDateTime.t(),
          updated_at: NaiveDateTime.t()
        }
end

With typed_ecto_schema you can just do:

defmodule Person do
  use TypedEctoSchema

  typed_schema "people" do
    field(:name, :string, enforce: true, null: false)
    field(:age, :integer) :: non_neg_integer() | nil
    field(:happy, :boolean, default: true, null: false)
    field(:phone, :string)
    belongs_to(:company, Company)
    timestamps(type: :naive_datetime_usec)
  end
end

I’d really appreciate some feedback.

Links:

Everything is still pretty new, so sorry for any bugs, poor docs or anything. I’ll try to fix everything.

5 Likes