simple_schema v1.1.0 SimpleSchema.Schema View Source
A module to convert a simple schema to JSON Schema
Basic:
iex> schema = %{name: :string,
...> value: {:integer, optional: true},
...> array: [:string],
...> map: {%{x: :integer, y: :integer}, optional: true},
...> param: {:any, optional: true}}
iex> SimpleSchema.Schema.to_json_schema(schema)
%{
"type" => "object",
"required" => ["array", "name"],
"additionalProperties" => false,
"properties" => %{
"name" => %{"type" => "string"},
"value" => %{"type" => "integer"},
"array" => %{
"type" => "array",
"items" => %{"type" => "string"},
},
"map" => %{
"type" => "object",
"required" => ["x", "y"],
"additionalProperties" => false,
"properties" => %{
"x" => %{"type" => "integer"},
"y" => %{"type" => "integer"},
},
},
"param" => %{
"type" => ["array", "boolean", "integer", "null", "number", "object", "string"],
},
},
}
With restrictions:
iex> schema = %{name: {:string, min_length: 8},
...> value: {:integer, optional: true, nullable: true, maximum: 10},
...> array: {[{:string, enum: ["aaa", "bbb"]}], min_items: 1}}
iex> SimpleSchema.Schema.to_json_schema(schema)
%{
"type" => "object",
"required" => ["array", "name"],
"additionalProperties" => false,
"properties" => %{
"name" => %{
"type" => "string",
"minLength" => 8,
},
"value" => %{
"type" => ["integer", "null"],
"maximum" => 10,
},
"array" => %{
"type" => "array",
"minItems" => 1,
"items" => %{
"type" => "string",
"enum" => [
"aaa",
"bbb",
],
}
},
},
}
Link to this section Summary
Functions
Convert validated JSON to a simple schema value
Convert a simple schema value to JSON value
Link to this section Types
Link to this type
array_type()
View Source
array_type() :: [simple_schema(), ...] | {[simple_schema(), ...], opts()}
Link to this type
map_type()
View Source
map_type() :: %{required(atom()) => simple_schema()} | {%{required(atom()) => simple_schema()}, opts()}
Link to this type
simple_schema()
View Source
simple_schema() :: boolean_type() | integer_type() | number_type() | null_type() | string_type() | map_type() | array_type() | any_type() | module_type()
Link to this section Functions
Convert validated JSON to a simple schema value.
If validation is passed, The JSON key should be all known atom except :any
type.
So the key can be converted by String.to_existing_atom/1
.
iex> schema = %{foo: %{bar: :integer}}
iex> SimpleSchema.Schema.from_json(schema, %{"foo" => %{"bar" => 10}})
{:ok, %{foo: %{bar: 10}}}
However, :any
can contains an arbitrary key, so do not convert a value of :any
.
iex> schema = %{foo: :any}
iex> SimpleSchema.Schema.from_json(schema, %{"foo" => %{"bar" => 10}})
{:ok, %{foo: %{"bar" => 10}}}
Convert a simple schema value to JSON value.