-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsimple_ecto_store.ex
More file actions
54 lines (45 loc) · 1.39 KB
/
simple_ecto_store.ex
File metadata and controls
54 lines (45 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
defmodule OkrApp.Store.SimpleEctoStore do
alias OkrApp.Repo
@methods [:all, :find, :create, :update, :delete]
defmacro __using__(opts) do
schema = Keyword.fetch!(opts, :schema)
only = Keyword.get(opts, :only, @methods) |> Enum.map(& {&1, true}) |> Enum.into(%{})
quote do
@schema unquote(schema)
if unquote(only[:all]) do
def all(params = %{}, opts \\ []) do
params = Enum.map(params, fn {k, v} -> {to_string(k), v} end) |> Enum.into(%{})
OkrApp.Query.ListQuery.get_query(@schema, params, opts)
|> Repo.all()
end
end
if unquote(only[:find]) do
def find(id) when is_bitstring(id) or is_integer(id) do
Repo.get(@schema, id)
|> case do
nil -> {:error, :not_found}
res -> {:ok, res}
end
end
end
if unquote(only[:create]) do
def create(params) do
@schema.create_changeset(params)
|> Repo.insert()
end
end
if unquote(only[:update]) do
def update(struct = %@schema{}, params) do
@schema.update_changeset(struct, params)
|> Repo.update()
end
end
if unquote(only[:delete]) do
def delete(struct = %@schema{}) do
Ecto.Changeset.change(struct, deleted_at: DateTime.utc_now())
|> Repo.update()
end
end
end
end
end