-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcrudry_context.ex
More file actions
323 lines (250 loc) · 9.61 KB
/
crudry_context.ex
File metadata and controls
323 lines (250 loc) · 9.61 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
defmodule Crudry.Context do
@moduledoc """
Generates CRUD functions to DRY Phoenix Contexts.
* Assumes `Ecto.Repo` is being used as the repository.
* Uses the Ecto Schema source name to generate the pluralized name for the functions, and the module name to generate the singular name.
This follows the same pattern as the [Mix.Tasks.Phx.Gen.Context](https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Gen.Context.html), so it should be straightforward to replace Phoenix's auto-generated functions with Crudry.
## Usage
To generate CRUD functions for a given schema, simply do
defmodule MyApp.MyContext do
alias MyApp.Repo
alias MyApp.MySchema
require Crudry.Context
Crudry.Context.generate_functions MySchema
end
And the context will have all these functions available:
defmodule MyApp.MyContext do
alias MyApp.Repo
alias MyApp.MySchema
require Crudry.Context
## Exists functions
def my_schema_exists?(id) do
import Ecto.Query, only: [from: 2]
query = from(x in MySchema, where: x.id == ^id)
Repo.exists?(query)
end
## Get functions
def get_my_schema(id, opts \\\\ []) do
assocs = opts[:assoc] || []
MySchema
|> Repo.get(id)
|> Repo.preload(assocs)
end
def get_my_schema!(id, opts \\\\ []) do
assocs = opts[:assoc] || []
MySchema
|> Repo.get!(id)
|> Repo.preload(assocs)
end
@deprecated "Use get_schema/2 instead"
def get_my_schema_with_assocs(id, assocs) do
MySchema
|> Repo.get(id)
|> Repo.preload(assocs)
end
@deprecated "Use get_schema!/2 instead"
def get_my_schema_with_assocs!(id, assocs) do
MySchema
|> Repo.get!(id)
|> Repo.preload(assocs)
end
def get_my_schema_by(clauses, opts \\\\ []) do
assocs = opts[:assoc] || []
MySchema
|> Repo.get_by(clauses)
|> Repo.preload(assocs)
end
def get_my_schema_by!(clauses, opts \\\\ []) do
assocs = opts[:assoc] || []
MySchema
|> Repo.get_by!(clauses)
|> Repo.preload(assocs)
end
@deprecated "Use get_my_schema_by/2 instead"
def get_my_schema_by_with_assocs(clauses, assocs) do
MySchema
|> Repo.get_by(clauses)
|> Repo.preload(assocs)
end
@deprecated "Use get_my_schema_by!/2 instead"
def get_my_schema_by_with_assocs!(clauses, assocs) do
MySchema
|> Repo.get_by!(clauses)
|> Repo.preload(assocs)
end
## List functions
def list_my_schemas() do
Repo.all(MySchema)
end
def list_my_schemas(opts) do
MySchema
|> Crudry.Query.list(opts)
|> Repo.all()
end
def list_my_schemas_with_assocs(assocs) do
MySchema
|> Repo.all()
|> Repo.preload(assocs)
end
def list_my_schemas_with_assocs(assocs, opts) do
MySchema
|> Crudry.Query.list(opts)
|> Repo.all()
|> Repo.preload(assocs)
end
def filter_my_schemas(filters) do
MySchema
|> Crudry.Query.filter(filters)
|> Repo.all()
end
def search_my_schemas(search_term) do
module_fields = MySchema.__schema__(:fields)
MySchema
|> Crudry.Query.search(search_term, module_fields)
|> Repo.all()
end
def count_my_schemas(opts \\\\ []) do
field = opts[:field] || :id
search = opts[:search]
search_fields = opts[:search_fields] || []
filters = opts[:filters] || %{}
MySchema
|> Crudry.Query.search(search, search_fields)
|> Crudry.Query.filter(filters)
|> Repo.aggregate(:count, field)
end
## Create functions
def create_my_schema(attrs) do
%MySchema{}
|> MySchema.changeset(attrs)
|> Repo.insert()
end
def create_my_schema!(attrs) do
%MySchema{}
|> MySchema.changeset(attrs)
|> Repo.insert!()
end
## Update functions
def update_my_schema(%MySchema{} = my_schema, attrs) do
my_schema
|> MySchema.changeset(attrs)
|> Repo.update()
end
def update_my_schema!(%MySchema{} = my_schema, attrs) do
my_schema
|> MySchema.changeset(attrs)
|> Repo.update!()
end
def update_my_schema_with_assocs(%MySchema{} = my_schema, attrs, assocs) do
my_schema
|> Repo.preload(assocs)
|> MySchema.changeset(attrs)
|> Repo.update()
end
def update_my_schema_with_assocs!(%MySchema{} = my_schema, attrs, assocs) do
my_schema
|> Repo.preload(assocs)
|> MySchema.changeset(attrs)
|> Repo.update!()
end
## Delete functions
def delete_my_schema(%MySchema{} = my_schema) do
my_schema
|> Ecto.Changeset.change()
|> check_assocs([])
|> Repo.delete()
end
def delete_my_schema!(%MySchema{} = my_schema) do
my_schema
|> Ecto.Changeset.change()
|> check_assocs([])
|> Repo.delete!()
end
# Function to check no_assoc_constraints, always generated.
defp check_assocs(changeset, nil), do: changeset
defp check_assocs(changeset, constraints) do
Enum.reduce(constraints, changeset, fn i, acc -> Ecto.Changeset.no_assoc_constraint(acc, i) end)
end
end
"""
@all_functions ~w(exists get list count search filter create update delete)a
# Always generate helper functions since they are used in the other generated functions
@helper_functions ~w(check_assocs)a
@doc """
Sets default options for the context.
## Options
* `:create` - the name of the changeset function used in the `create` function.
Defaults to `:changeset`.
* `:update` - the name of the changeset function used in the `update` function.
Defaults to `:changeset`.
* `:only` - list of functions to be generated. If not empty, functions not
specified in this list are not generated. Defaults to `[]`.
* `:except` - list of functions to not be generated. If not empty, only functions not specified
in this list will be generated. Defaults to `[]`.
The accepted values for `:only` and `:except` are: `#{inspect(@all_functions)}`.
## Examples
iex> Crudry.Context.default create: :create_changeset, update: :update_changeset
:ok
iex> Crudry.Context.default only: [:create, :list]
:ok
iex> Crudry.Context.default except: [:get!, :list, :delete]
:ok
"""
defmacro default(opts) do
Module.put_attribute(__CALLER__.module, :create_changeset, opts[:create])
Module.put_attribute(__CALLER__.module, :update_changeset, opts[:update])
Module.put_attribute(__CALLER__.module, :only, opts[:only])
Module.put_attribute(__CALLER__.module, :except, opts[:except])
Module.put_attribute(__CALLER__.module, :repo, opts[:repo])
end
@doc """
Generates CRUD functions for the `schema_module`.
Custom options can be given. To see the available options, refer to the documenation of `Crudry.Context.default/1`.
There is also one extra option that cannot be set by default:
* `check_constraints_on_delete` - list of associations that must be empty to allow deletion.
`Ecto.Changeset.no_assoc_constraint` will be called for each association before deleting. Defaults to `[]`.
## Examples
Suppose we want to implement basic CRUD functionality for a User schema,
exposed through an Accounts context:
defmodule MyApp.Accounts do
alias MyApp.Repo
require Crudry.Context
# Assuming Accounts.User implements a `changeset/2` function, used both to create and update a user.
Crudry.Context.generate_functions Accounts.User
end
Now, suppose the changeset for create and update are different, and we want to delete the record only if the association `has_many :assocs` is empty:
defmodule MyApp.MyContext do
alias MyApp.Repo
alias MyApp.MySchema
require Crudry.Context
Crudry.Context.generate_functions MySchema,
create: :create_changeset,
update: :update_changeset,
check_constraints_on_delete: [:assocs]
end
"""
defmacro generate_functions(schema_module, opts \\ []) do
opts = Keyword.merge(load_default(__CALLER__.module), opts)
name = Helper.get_underscored_name(schema_module)
pluralized_name = Helper.get_pluralized_name(schema_module, __CALLER__)
for func <- Helper.get_functions_to_be_generated(__CALLER__.module, @all_functions, @helper_functions, opts) do
ContextFunctionsGenerator.generate_function(func, name, pluralized_name, schema_module, opts)
end
end
# Load user-defined defaults or fall back to the library's default.
defp load_default(module) do
create_changeset = Module.get_attribute(module, :create_changeset)
update_changeset = Module.get_attribute(module, :update_changeset)
only = Module.get_attribute(module, :only)
except = Module.get_attribute(module, :except)
repo = Module.get_attribute(module, :repo)
[
create: create_changeset || :changeset,
update: update_changeset || :changeset,
only: only || [],
except: except || [],
check_constraints_on_delete: [],
repo: repo,
]
end
end