|
| 1 | +# Add primary key and timestamps types to your Ecto schema |
| 2 | + |
| 3 | + |
| 4 | +## Implementation |
| 5 | + |
| 6 | +This plugin use `c:TypedStructor.Plugin.before_definition/2` callback to |
| 7 | +inject the primary key and timestamps fields to the type definition. |
| 8 | + |
| 9 | +```elixir |
| 10 | +defmodule MyApp.TypedStructor.Plugins.PrimaryKeyAndTimestamps do |
| 11 | + use TypedStructor.Plugin |
| 12 | + |
| 13 | + @impl TypedStructor.Plugin |
| 14 | + defmacro before_definition(definition, _opts) do |
| 15 | + quote do |
| 16 | + Map.update!(unquote(definition), :fields, fn fields -> |
| 17 | + # Assume that the primary key is an integer |
| 18 | + primary_key = [name: :id, type: quote(do: integer()), enforce: true] |
| 19 | + |
| 20 | + # Add two default timestamps |
| 21 | + timestamps = [ |
| 22 | + [name: :inserted_at, type: quote(do: NaiveDateTime.t()), enforce: true], |
| 23 | + [name: :updated_at, type: quote(do: NaiveDateTime.t()), enforce: true] |
| 24 | + ] |
| 25 | + |
| 26 | + [primary_key | fields] ++ timestamps |
| 27 | + end) |
| 28 | + end |
| 29 | + end |
| 30 | +end |
| 31 | +``` |
| 32 | + |
| 33 | +## Usage |
| 34 | + |
| 35 | +```elixir |
| 36 | +defmodule MyApp.User do |
| 37 | + use TypedStructor |
| 38 | + use Ecto.Schema |
| 39 | + |
| 40 | + # disable struct creation or it will conflict with the Ecto schema |
| 41 | + typed_structor define_struct: false do |
| 42 | + # register the plugin |
| 43 | + plugin MyApp.TypedStructor.Plugins.PrimaryKeyAndTimestamps |
| 44 | + |
| 45 | + field :name, String.t() |
| 46 | + field :age, integer(), enforce: true # There is always a non-nil value |
| 47 | + end |
| 48 | + |
| 49 | + schema "source" do |
| 50 | + field :name, :string |
| 51 | + field :age, :integer, default: 20 |
| 52 | + |
| 53 | + timestamps() |
| 54 | + end |
| 55 | +end |
| 56 | +``` |
0 commit comments