Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add external format validators option #85

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,39 @@ ErrorType}` where
* ErrorType is an atom such as `missing_id_field` or a tuple such as
`{wrong_type_dependency, Dependency}`.

## Custom string format validators
Built-in format validators, like `ipv4`, `date-time` are often not enough for `string` type
and usage of pattern (regexps) is not convenient.

Custom string format validator could be used with `{ext_format_validators, Validators}` option.
* `Validators` is a map of `CustomFormatName => ValidationFunction` pairs (`proplists` are also supported)
* `CustomFormatName` is a string that must be used in schema as a `format` value for `string` type
* `ValidationFunction` takes `string` value and must return `ok` or `error` atom indicating validation result

Simple example:
```erlang
1> Schema = #{
1> <<"type">> => <<"object">>,
1> <<"properties">> => #{
1> <<"foo">> => #{
1> <<"type">> => <<"string">>,
1> <<"format">> => <<"ipv4_and_port">>
1> }
1> }
1> },
1> Validators = #{
1> <<"ipv4_and_port">> => fun(<<"127.0.0.1:1234">>) -> ok; (_Else) -> error end
1> },
1> Options = [{ext_format_validators, Validators}],
1> jesse:validate_with_schema(Schema, #{<<"foo">> => <<"127.0.0.1:1234">>}, Options).
{ok,#{<<"foo">> => <<"127.0.0.1:1234">>}}
2> jesse:validate_with_schema(Schema, #{<<"foo">> => <<"Hello, Joe!">>}, Options).
{error,[{data_invalid,#{<<"format">> => <<"ipv4_and_port">>,
<<"type">> => <<"string">>},
wrong_format,<<"Hello, Joe!">>,
[<<"foo">>]}]}
```

## Caveats

* pattern and patternProperty attributes:
Expand Down
14 changes: 13 additions & 1 deletion src/jesse.erl
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
, error_handler/0
, error_list/0
, external_validator/0
, ext_format_validator/0
, ext_format_validators/0
, json_term/0
, schema/0
, schema_id/0
Expand Down Expand Up @@ -71,7 +73,16 @@
-type external_validator() :: fun((json_term(), any()) -> any())
| undefined.

%% github.com/erlang/otp/blob/OTP-20.2.3/lib/inets/doc/src/http_uri.xml#L57
-type ext_format_validator() :: fun((json_term()) -> ok | error).

-ifndef(erlang_deprecated_types).
-type ext_format_validators() :: [{binary(), ext_format_validator()}]
| #{binary() => ext_format_validator()}.
-else.
-type ext_format_validators() :: [{binary(), ext_format_validator()}].
-endif.

%%github.com/erlang/otp/blob/OTP-20.2.3/lib/inets/doc/src/http_uri.xml#L57
-type http_uri_uri() :: string() | unicode:unicode_binary().

-type json_term() :: term().
Expand All @@ -95,6 +106,7 @@
| {default_schema_ver, schema_ver()}
| {error_handler, error_handler()}
| {external_validator, external_validator()}
| {ext_format_validators, ext_format_validators()}
| {meta_schema_ver, schema_ver()}
| {parser_fun, parser_fun()}
| {schema_loader_fun, schema_loader_fun()}.
Expand Down
38 changes: 30 additions & 8 deletions src/jesse_state.erl
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
-export([ add_to_path/2
, get_allowed_errors/1
, get_external_validator/1
, get_ext_format_validator/2
, get_current_path/1
, get_current_schema/1
, get_current_schema_id/1
Expand Down Expand Up @@ -59,6 +60,7 @@
, error_handler :: jesse:error_handler()
, error_list :: jesse:error_list()
, external_validator :: jesse:external_validator()
, ext_format_validators :: jesse:ext_format_validators()
, id :: jesse:schema_id()
, root_schema :: jesse:schema()
, schema_loader_fun :: jesse:schema_loader_fun()
Expand Down Expand Up @@ -142,18 +144,23 @@ new(JsonSchema, Options) ->
ExternalValidator = proplists:get_value( external_validator
, Options
),
ExtFormatValidators = proplists:get_value( ext_format_validators
, Options
, #{}
),
LoaderFun = proplists:get_value( schema_loader_fun
, Options
, ?default_schema_loader_fun
),
NewState = #state{ root_schema = JsonSchema
, current_path = []
, allowed_errors = AllowedErrors
, error_list = []
, error_handler = ErrorHandler
, default_schema_ver = DefaultSchemaVer
, schema_loader_fun = LoaderFun
, external_validator = ExternalValidator
NewState = #state{ root_schema = JsonSchema
, current_path = []
, allowed_errors = AllowedErrors
, error_list = []
, error_handler = ErrorHandler
, default_schema_ver = DefaultSchemaVer
, schema_loader_fun = LoaderFun
, external_validator = ExternalValidator
, ext_format_validators = ExtFormatValidators
},
set_current_schema(NewState, JsonSchema).

Expand Down Expand Up @@ -399,6 +406,21 @@ load_schema(#state{schema_loader_fun = LoaderFun}, SchemaURI) ->
get_external_validator(#state{external_validator = Fun}) ->
Fun.

-spec get_ext_format_validator(binary(), state()) ->
jesse:external_format_validator() | undefined.
-ifndef(erlang_deprecated_types).
get_ext_format_validator(Format, #state{ext_format_validators = Validators})
when is_map(Validators) ->
maps:get(Format, Validators, undefined);
get_ext_format_validator(Format, #state{ext_format_validators = Validators})
when is_list(Validators) ->
proplists:get_value(Format, Validators, undefined).
-else.
get_ext_format_validator(Format, #state{ext_format_validators = Validators})
when is_list(Validators) ->
proplists:get_value(Format, Validators, undefined).
-endif.

%% @private
-ifdef(OTP_RELEASE). %% OTP 21+
parse_ref(RefBin) ->
Expand Down
15 changes: 13 additions & 2 deletions src/jesse_validator_draft3.erl
Original file line number Diff line number Diff line change
Expand Up @@ -837,8 +837,8 @@ check_enum(Value, Enum, State) ->
handle_data_invalid(?not_in_enum, Value, State)
end.

check_format(_Value, _Format, State) ->
State.
check_format(Value, Format, State) ->
maybe_external_check_format(Value, Format, State).

%% @doc 5.24. divisibleBy
%%
Expand Down Expand Up @@ -1052,3 +1052,14 @@ maybe_external_check_value(Value, State) ->
Fun ->
Fun(Value, State)
end.

maybe_external_check_format(Value, Format, State) ->
case jesse_state:get_ext_format_validator(Format, State) of
undefined -> State;
Fun when is_function(Fun, 1) ->
abogosyan marked this conversation as resolved.
Show resolved Hide resolved
case Fun(Value) of
ok -> State;
error ->
handle_data_invalid(?wrong_format, Value, State)
abogosyan marked this conversation as resolved.
Show resolved Hide resolved
end
end.
15 changes: 13 additions & 2 deletions src/jesse_validator_draft4.erl
Original file line number Diff line number Diff line change
Expand Up @@ -980,8 +980,8 @@ check_format(Value, _Format = <<"ipv6">>, State) when is_binary(Value) ->
check_format(Value, _Format = <<"uri">>, State) when is_binary(Value) ->
%% not yet supported
State;
check_format(_Value, _Format, State) ->
State.
check_format(Value, Format, State) ->
maybe_external_check_format(Value, Format, State).

%% @doc 5.1.1. multipleOf
%%
Expand Down Expand Up @@ -1380,3 +1380,14 @@ maybe_external_check_value(Value, State) ->
Fun ->
Fun(Value, State)
end.

maybe_external_check_format(Value, Format, State) ->
abogosyan marked this conversation as resolved.
Show resolved Hide resolved
case jesse_state:get_ext_format_validator(Format, State) of
undefined -> State;
Fun when is_function(Fun, 1) ->
case Fun(Value) of
ok -> State;
error ->
handle_data_invalid(?wrong_format, Value, State)
end
end.
101 changes: 101 additions & 0 deletions test/jesse_schema_validator_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,57 @@ schema_unsupported_test() ->
, jesse_schema_validator:validate(UnsupportedSchema, Json, [])
).

external_format_validator_test() ->
[ external_format_validator_test_draft(URI)
|| URI <- [ <<"http://json-schema.org/draft-03/schema#">>
, <<"http://json-schema.org/draft-04/schema#">>
]
].

external_format_validator_test_draft(URI) ->
CustomFormatSchema = [
{<<"type">>, <<"string">>},
{<<"format">>, <<"ipv4_and_port">>}
],

Schema = {[
{<<"$schema">>, URI},
{<<"type">>, <<"object">>},
{<<"properties">>, {[
{<<"foo">>, CustomFormatSchema}
]}}
]},

Options = [{
ext_format_validators,
[{
<<"ipv4_and_port">>,
fun(<<"127.0.0.1:1234">>) -> ok; (_Else) -> error end
}]
}],

ValidJson = {[
{<<"foo">>, <<"127.0.0.1:1234">>}
]},

?assertEqual(
{ok, ValidJson},
jesse_schema_validator:validate(Schema, ValidJson, Options)
),

InvalidJson = {[
{<<"foo">>, <<"Hello, Joe!">>}
]},

?assertThrow([{
data_invalid,
CustomFormatSchema,
wrong_format,
<<"Hello, Joe!">>,
[<<"foo">>]
}],
jesse_schema_validator:validate(Schema, InvalidJson, Options)).

-ifndef(erlang_deprecated_types).
-ifndef(COMMON_TEST). % see Emakefile
map_schema_test() ->
Expand Down Expand Up @@ -270,6 +321,12 @@ map_data_test() ->
]
].

map_external_format_validator_test() ->
[ map_external_format_validator_test_draft(URI)
|| URI <- [ <<"http://json-schema.org/draft-03/schema#">>
, <<"http://json-schema.org/draft-04/schema#">>
]
].

map_data_test_draft(URI) ->
Schema = {[ {<<"$schema">>, URI}
Expand Down Expand Up @@ -325,5 +382,49 @@ map_data_test_draft(URI) ->
, [{allowed_errors, infinity}]
)).

map_external_format_validator_test_draft(URI) ->
CustomFormatSchema = #{
<<"type">> => <<"string">>,
<<"format">> => <<"ipv4_and_port">>
},

Schema = #{
<<"$schema">> => URI,
<<"type">> => <<"object">>,
<<"properties">> => #{
<<"foo">> => CustomFormatSchema
}
},

Options = [{
ext_format_validators,
#{
<<"ipv4_and_port">> =>
fun(<<"127.0.0.1:1234">>) -> ok; (_Else) -> error end
}
}],

ValidJson = #{
<<"foo">> => <<"127.0.0.1:1234">>
},
?assertEqual(
{ok, ValidJson},
jesse_schema_validator:validate(Schema, ValidJson, Options)
),

InvalidJson = #{
<<"foo">> => <<"Hello, Joe!">>
},

?assertThrow([{
data_invalid,
CustomFormatSchema,
wrong_format,
<<"Hello, Joe!">>,
[<<"foo">>]
}],
jesse_schema_validator:validate(Schema, InvalidJson, Options)).

-endif.
-endif.