-
Notifications
You must be signed in to change notification settings - Fork 9
/
json_schema.ex
220 lines (173 loc) · 5.61 KB
/
json_schema.ex
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
defmodule Xema.JsonSchema do
@moduledoc """
Converts a JSON Schema to Xema source.
"""
alias Xema.{
JsonSchema.Validator,
Schema,
SchemaError
}
@type json_schema :: true | false | map
@type opts :: [draft: String.t()]
@drafts ~w(draft4 draft6 draft7)
@schema ~w(
additional_items
additional_properties
property_names
not
if
then
else
contains
items
)a
@schemas ~w(
all_of
any_of
one_of
items
)a
@schema_map ~w(
definitions
pattern_properties
properties
)a
@keywords Schema.keywords()
|> Enum.map(&to_string/1)
|> ConvCase.to_camel_case()
|> List.delete("ref")
|> List.delete("schema")
|> Enum.concat(["$ref", "$id", "$schema"])
@doc """
This function converts a JSON Schema in Xema schema source. The argument
`json_schema` is expected as a decoded JSON Schema.
All keys that are not standard JSON Schema keywords have to be known atoms. If
the schema has additional keys that are unknown atoms the option
`atom: :force` is needed. In this case the atoms will be created. This is not
needed for keys expected by JSON Schema (e.g. in properties)
Options:
* `:draft` specifies the draft to check the given JSON Schema. Possible values
are `"draft4"`, `"draft6"`, and `"draft7"`, default is `"draft7"`. If
`:draft` not set and the schema contains `$schema` then the value for
`$schema` is used for this option.
* `:atom` creates atoms for unknown atoms when set to `:force`. This is just
needed for additional JSON Schema keywords.
## Examples
iex> Xema.JsonSchema.to_xema(%{"type" => "integer", "minimum" => 5})
{:integer, [minimum: 5]}
iex> schema = %{
...> "type" => "object",
...> "properties" => %{"foo" => %{"type" => "integer"}}
...> }
iex> Xema.JsonSchema.to_xema(schema)
{:map, [keys: :strings, properties: %{"foo" => :integer}]}
iex> Xema.JsonSchema.to_xema(%{"type" => "integer", "foo" => "bar"}, atom: :force)
{:integer, [foo: "bar"]}
"""
@spec to_xema(json_schema, opts) :: atom | tuple
def to_xema(json_schema, opts \\ []) do
draft = draft(json_schema, opts)
case Validator.validate(draft, json_schema) do
:ok ->
do_to_xema(json_schema, opts)
{:error, :unknown} ->
raise "unknown draft #{inspect(draft)}, has to be one of #{inspect(@drafts)}"
{:error, reason} ->
raise SchemaError, reason
end
end
defp do_to_xema(json, opts) when is_map(json) do
{type, json} = type(json)
cond do
Enum.empty?(json) ->
type
type == :map ->
{:map, json |> Map.put("keys", :strings) |> schema(opts)}
true ->
{type, schema(json, opts)}
end
end
defp do_to_xema(json, _) when is_boolean(json), do: json
defp type(map) do
{type, map} = Map.pop(map, "type", :any)
{type_to_atom(type), map}
end
defp draft(json_schema, opts) when is_map(json_schema) do
draft = Map.get(json_schema, "$schema", "draft7")
Keyword.get(opts, :draft, draft)
end
defp draft(_json_schema, opts), do: Keyword.get(opts, :draft, "draft7")
defp type_to_atom(list) when is_list(list), do: Enum.map(list, &type_to_atom/1)
defp type_to_atom("object"), do: :map
defp type_to_atom("array"), do: :list
defp type_to_atom("null"), do: nil
defp type_to_atom(type) when is_binary(type), do: to_existing_atom(type)
defp type_to_atom(type), do: type
defp schema(json, opts) do
json
|> Enum.map(&rule(&1, opts))
|> Keyword.new()
end
# handles all rules with a regular keyword
defp rule({key, value}, opts) when key in @keywords do
key
|> String.trim_leading("$")
|> ConvCase.to_snake_case()
|> to_existing_atom(opts)
|> rule(value, opts)
end
# handles all rules without a regular keyword
defp rule({key, value}, opts) when is_binary(key) and is_map(value) do
value =
case schema?(value) do
true -> do_to_xema(value, opts)
false -> schema(value, opts)
end
{to_existing_atom(key, opts), value}
end
defp rule({key, value}, opts), do: {to_existing_atom(key, opts), value}
defp rule(:format, value, _) do
format = value |> ConvCase.to_snake_case() |> to_existing_atom(maybe: true)
case is_atom(format) do
true -> {:format, format}
false -> {:format, :unsupported}
end
end
defp rule(:dependencies, value, opts) do
value =
Enum.into(value, %{}, fn
{key, value} when is_map(value) -> {key, do_to_xema(value, opts)}
{key, value} -> {key, value}
end)
{:dependencies, value}
end
defp rule(key, value, opts) when key in @schema_map do
{key, Enum.into(value, %{}, fn {key, value} -> {key, do_to_xema(value, opts)} end)}
end
defp rule(key, value, opts) when key in @schemas and is_list(value) do
{key, Enum.map(value, &do_to_xema(&1, opts))}
end
defp rule(key, value, opts) when key in @schema do
{key, do_to_xema(value, opts)}
end
defp rule(key, value, _), do: {key, value}
defp schema?(value) do
value |> Map.keys() |> Enum.any?(fn key -> Enum.member?(@keywords, key) end)
end
defp to_existing_atom(str, opts \\ []) do
case Keyword.get(opts, :atom, :existing) do
:existing -> String.to_existing_atom(str)
:force -> String.to_atom(str)
end
rescue
_ ->
case Keyword.get(opts, :maybe, false) do
true ->
str
false ->
reraise SchemaError,
"All additional schema keys must be existing atoms. Missing atom for #{str}",
__STACKTRACE__
end
end
end