Skip to content

Commit 0db6ebc

Browse files
committed
docs: add Add primary key and timestamps types to your Ecto schema guide
1 parent 3f90b8f commit 0db6ebc

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
```

mix.exs

+2-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ defmodule TypedStructor.MixProject do
3131
"guides/migrate_from_typed_struct.md",
3232

3333
# plugins
34-
"guides/plugins/type_only_on_ecto_schema.md"
34+
"guides/plugins/type_only_on_ecto_schema.md",
35+
"guides/plugins/primary_key_and_timestamps.md"
3536
]
3637
],
3738
package: [

0 commit comments

Comments
 (0)