-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathschemecto.ex
More file actions
471 lines (375 loc) · 13.4 KB
/
Copy pathschemecto.ex
File metadata and controls
471 lines (375 loc) · 13.4 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
defmodule Schemecto do
@moduledoc """
Schemaless Ecto changesets with support for nesting and JSON Schemas.
"""
@doc """
Creates a new schemaless changeset with the given field definitions.
If parameters are given, they are cast into the changeset according
to fields. Parameters are a keyword list, a map of string or atom keys,
or nil.
## Parameters
* `fields` - List of field definitions. Each field is a map with:
* `:name` - Field name (required)
* `:type` - Field type (required)
* `:description` - Human-readable description (optional)
* `:title` - Human-readable title (optional)
* `:deprecated` - Boolean indicating if field is deprecated (optional)
* `:default` - Default value for the field (optional)
## Examples
fields = [
%{name: :name, type: :string, title: "Full Name"},
%{name: :age, type: :integer, default: 0, description: "Age in years"}
]
params = %{"name" => "John", "age" => 30}
changeset = Schemecto.new(fields, params)
"""
def new(fields, params \\ %{})
when is_list(fields) and (is_list(params) or is_map(params) or params == nil) do
changeset = build_changeset(fields)
if params == [] or params == %{} or params == nil do
changeset
else
Ecto.Changeset.cast(changeset, params, Map.keys(changeset.types))
end
end
@doc """
Defines a nested validation for cardinality `one`.
## Parameters
* `fields` - List of field definitions for the nested changeset
* `opts` - Keyword list of options:
* `:with` - A 1-arity function that receives a changeset
with the parameters already cast into them (if any) (required)
## Examples
def validate_address(changeset) do
changeset
|> Ecto.Changeset.validate_required([:street, :city])
end
fields = [
%{name: :name, type: :string},
%{name: :email, type: :string},
%{name: :address, type: Schemecto.one(
[
%{name: :street, type: :string},
%{name: :city, type: :string},
%{name: :zip, type: :string}
],
with: &validate_address/1
)}
]
changeset = Schemecto.new(fields, params)
"""
def one(fields, opts) when is_list(fields) and is_list(opts) do
function = Keyword.fetch!(opts, :with)
if not is_function(function, 1) do
raise ArgumentError,
"expected :with option to be a 1-arity function, got: #{inspect(function)}"
end
Ecto.ParameterizedType.init(Schemecto.One, %{
changeset: build_changeset(fields),
with: function
})
end
@doc """
Defines a nested validation for cardinality :many.
## Parameters
* `fields` - List of field definitions for each nested changeset
* `opts` - Keyword list of options:
* `:with` - A 2-arity function that receives a changeset and params,
and returns a validated changeset (required)
## Examples
def validate_tag(changeset) do
changeset
|> Ecto.Changeset.validate_required([:name])
end
fields = [
%{name: :title, type: :string},
%{name: :tags, type: Schemecto.many(
[
%{name: :name, type: :string},
%{name: :color, type: :string}
],
with: &validate_tag/1
)}
]
changeset = Schemecto.new(fields, params)
"""
def many(fields, opts) when is_list(fields) and is_list(opts) do
function = Keyword.fetch!(opts, :with)
if not is_function(function, 1) do
raise ArgumentError,
"expected :with option to be a 1-arity function, got: #{inspect(function)}"
end
Ecto.ParameterizedType.init(Schemecto.Many, %{
changeset: build_changeset(fields),
with: function
})
end
@doc """
Defines a validation for maps of arbitrary keys to values of the given type.
Values are cast with `Ecto.Type.cast/2`, so any castable Ecto type is
supported, including `{:array, type}`, `Ecto.Enum`, and nested
`Schemecto.one/2` types.
## Examples
fields = [
%{name: :flags, type: Schemecto.map_of(:boolean)}
]
changeset = Schemecto.new(fields, params)
"""
def map_of(fields) when is_list(fields) do
raise ArgumentError,
"a list of fields requires a :with option, use map_of(fields, with: fun)"
end
def map_of(type) do
Ecto.ParameterizedType.init(Schemecto.MapOf, %{type: type})
end
@doc """
Defines a validation for maps of arbitrary keys to nested values.
## Parameters
* `fields` - List of field definitions for each nested value
* `opts` - Keyword list of options:
* `:with` - A 1-arity function that receives a changeset
with the parameters already cast into them (if any) (required)
## Examples
def validate_endpoint(changeset) do
changeset
|> Ecto.Changeset.validate_required([:host])
|> Ecto.Changeset.validate_number(:port, greater_than: 0, less_than: 65_536)
end
fields = [
%{
name: :endpoints,
type: Schemecto.map_of(
[
%{name: :host, type: :string},
%{name: :port, type: :integer, default: 443}
],
with: &validate_endpoint/1
)
}
]
changeset = Schemecto.new(fields, params)
"""
def map_of(fields, opts) when is_list(fields) and is_list(opts) do
function = Keyword.fetch!(opts, :with)
if not is_function(function, 1) do
raise ArgumentError,
"expected :with option to be a 1-arity function, got: #{inspect(function)}"
end
Ecto.ParameterizedType.init(Schemecto.MapOf, %{
changeset: build_changeset(fields),
with: function
})
end
# Builds a changeset from field definitions
defp build_changeset(fields) do
{types, defaults, metadata_validations} = extract_field_info(fields)
changeset = Ecto.Changeset.change({Map.new(defaults), types}, %{})
%{changeset | validations: metadata_validations ++ changeset.validations}
end
# Extracts types, defaults, and metadata validations from field definitions
defp extract_field_info(fields) do
Enum.reduce(fields, {%{}, [], []}, fn field, {types_acc, defaults_acc, metadata_acc} ->
name = Map.fetch!(field, :name)
type = Map.fetch!(field, :type)
if Map.has_key?(types_acc, name) do
raise ArgumentError, "duplicate field #{inspect(name)} given to Schemecto"
end
types_acc = Map.put(types_acc, name, type)
defaults_acc =
case field do
%{default: default} -> [{name, default} | defaults_acc]
%{} -> defaults_acc
end
metadata =
Enum.flat_map(field, fn
{:name, name} when is_atom(name) ->
[]
{:type, _type} ->
[]
{:default, _} ->
[]
{:deprecated, boolean} when is_boolean(boolean) ->
[{:deprecated, boolean}]
{:title, string} when is_binary(string) ->
[{:title, string}]
{:description, string} when is_binary(string) ->
[{:description, string}]
{name, _value} ->
raise ArgumentError, "unknown key #{inspect(name)} in #{inspect(field)}"
end)
metadata_acc =
if metadata != [] do
[{name, {:schemecto_metadata, Map.new(metadata)}} | metadata_acc]
else
metadata_acc
end
{types_acc, defaults_acc, metadata_acc}
end)
end
@doc """
Converts a changeset's types into a JSON schema.
Takes a changeset and returns a JSON schema based on the changeset's metadata.
Note the "$schema" property is not included in the schema for easier embedding,
but it is recommended to be set to "https://json-schema.org/draft/2020-12/schema".
## Examples
iex> fields = [
...> %{name: :name, type: :string, title: "Full Name"},
...> %{name: :age, type: :integer}
...> ]
iex> changeset = Schemecto.new(fields)
iex> Schemecto.to_json_schema(changeset)
%{
"type" => "object",
"properties" => %{
"name" => %{"type" => "string", "title" => "Full Name"},
"age" => %{"type" => "integer"}
}
}
"""
def to_json_schema(%Ecto.Changeset{types: types, required: required, validations: validations}) do
properties =
Map.new(types, fn {field, type} ->
schema =
validations
|> Keyword.get_values(field)
|> Enum.reduce(type_to_json_schema(type), &apply_validation/2)
{to_string(field), schema}
end)
result = %{
"type" => "object",
"properties" => properties
}
if required == [] do
result
else
required_fields = Enum.map(required, &to_string/1)
Map.put(result, "required", required_fields)
end
end
# For compatibility with Ecto earlier than v3.12
defp type_to_json_schema({:parameterized, mod, arg}),
do: type_to_json_schema({:parameterized, {mod, arg}})
defp type_to_json_schema({:parameterized, {Ecto.Enum, params}} = type) do
Ecto.Enum.type(params)
|> type_to_json_schema()
|> Map.put("enum", Ecto.Enum.dump_values(%{field: type}, :field))
end
defp type_to_json_schema({:parameterized, {Schemecto.One, %{changeset: changeset, with: fun}}}) do
changeset |> fun.() |> to_json_schema()
end
defp type_to_json_schema({:parameterized, {Schemecto.Many, %{changeset: changeset, with: fun}}}) do
%{
"type" => "array",
"items" => changeset |> fun.() |> to_json_schema()
}
end
defp type_to_json_schema(
{:parameterized, {Schemecto.MapOf, %{changeset: changeset, with: fun}}}
) do
%{
"type" => "object",
"additionalProperties" => changeset |> fun.() |> to_json_schema()
}
end
defp type_to_json_schema({:parameterized, {Schemecto.MapOf, %{type: type}}}) do
%{
"type" => "object",
"additionalProperties" => type_to_json_schema(type)
}
end
# For all other types, get the underlying type using Ecto.Type.type/1
defp type_to_json_schema(type) do
try do
Ecto.Type.type(type)
rescue
UndefinedFunctionError ->
raise ArgumentError, "unknown type given to to_json_schema: #{inspect(type)}"
else
type -> do_type_to_json_schema(type)
end
end
defp do_type_to_json_schema(:string), do: %{"type" => "string"}
defp do_type_to_json_schema(:integer), do: %{"type" => "integer"}
defp do_type_to_json_schema(:float), do: %{"type" => "number"}
defp do_type_to_json_schema(:decimal), do: %{"type" => "number"}
defp do_type_to_json_schema(:boolean), do: %{"type" => "boolean"}
defp do_type_to_json_schema(:map), do: %{"type" => "object"}
defp do_type_to_json_schema({:array, :any}) do
%{
"type" => "array",
"items" => %{}
}
end
defp do_type_to_json_schema({:array, inner_type}) do
%{
"type" => "array",
"items" => type_to_json_schema(inner_type)
}
end
defp do_type_to_json_schema(unknown) do
raise ArgumentError, "unknown type given to to_json_schema: #{inspect(unknown)}"
end
# Validation appliers for each type
defp apply_validation({:format, regex}, schema) do
unless schema["type"] == "string" do
raise ArgumentError, "validate_format can only be applied to string fields"
end
Map.put(schema, "pattern", Regex.source(regex))
end
defp apply_validation({:inclusion, values}, schema) when is_list(values) do
Map.put(schema, "enum", values)
end
defp apply_validation({:inclusion, first..last//1}, schema) do
schema
|> Map.put("minimum", first)
|> Map.put("maximum", last)
end
defp apply_validation({:length, opts}, schema) do
case schema["type"] do
"string" -> apply_string_length(schema, opts)
"array" -> apply_array_length(schema, opts)
"object" -> apply_object_length(schema, opts)
_ -> schema
end
end
defp apply_validation({:number, opts}, schema) do
Enum.reduce(opts, schema, fn
{:greater_than, val}, acc -> Map.put(acc, "exclusiveMinimum", val)
{:less_than, val}, acc -> Map.put(acc, "exclusiveMaximum", val)
{:greater_than_or_equal_to, val}, acc -> Map.put(acc, "minimum", val)
{:less_than_or_equal_to, val}, acc -> Map.put(acc, "maximum", val)
{:equal_to, val}, acc -> Map.put(acc, "const", val)
_unknown, acc -> acc
end)
end
defp apply_validation({:subset, values}, schema) do
update_in(schema["items"], fn items ->
Map.put(items || %{}, "enum", values)
end)
end
defp apply_validation({:schemecto_metadata, metadata}, schema) do
schema
|> maybe_put("description", Map.get(metadata, :description))
|> maybe_put("title", Map.get(metadata, :title))
|> maybe_put("deprecated", Map.get(metadata, :deprecated))
end
defp apply_validation(_unknown, schema), do: schema
defp maybe_put(schema, _key, nil), do: schema
defp maybe_put(schema, key, value), do: Map.put(schema, key, value)
# Type-specific length handlers
defp apply_string_length(schema, opts) do
schema
|> maybe_put("minLength", opts[:is] || opts[:min])
|> maybe_put("maxLength", opts[:is] || opts[:max])
end
defp apply_array_length(schema, opts) do
schema
|> maybe_put("minItems", opts[:is] || opts[:min])
|> maybe_put("maxItems", opts[:is] || opts[:max])
end
defp apply_object_length(schema, opts) do
schema
|> maybe_put("minProperties", opts[:is] || opts[:min])
|> maybe_put("maxProperties", opts[:is] || opts[:max])
end
end