0
Fork 0
mirror of https://github.com/ninenines/cowboy.git synced 2025-07-14 12:20:24 +00:00

Improve the interface for constraints

There are two important changes in this commit.

Constraints are now producing an error tuple. This error tuple
in turn can be provided to a function for formatting a human
readable error message. Both the error tuple and the formatting
code are controlled by and part of the constraint function.

Constraints now also implement the reverse operation.
When constraint functions only validate, the reverse operation
will be the same as the forward operation. When they also do
some conversion then the reverse operation will reverse it.

Since constraints are now performing 3 different operations
(forward, reverse and format_error), they now take the form
of a function accepting two separate arguments. The operation
is the first argument.

In addition, the return value was changed to take the form
of {ok, Value} | {error, Reason}. The value must be returned
as-is if it was not modified.
This commit is contained in:
Loïc Hoguin 2017-06-28 17:38:17 +02:00
parent 3eb7693e4f
commit c221730371
No known key found for this signature in database
GPG key ID: 71366FF21851DF03
3 changed files with 156 additions and 45 deletions

View file

@ -780,10 +780,10 @@ filter([Key|Tail], Map) ->
true = maps:is_key(Key, Map),
filter(Tail, Map).
filter_constraints(Tail, Map, Key, Value, Constraints) ->
case cowboy_constraints:validate(Value, Constraints) of
true ->
filter(Tail, Map);
{true, Value2} ->
filter(Tail, Map#{Key => Value2})
filter_constraints(Tail, Map, Key, Value0, Constraints) ->
case cowboy_constraints:validate(Value0, Constraints) of
{ok, Value} ->
filter(Tail, Map#{Key => Value});
{error, Reason} ->
exit(Reason)
end.