cowboy_constraints.erl 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. %% Copyright (c) 2014, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(cowboy_constraints).
  15. -export([validate/2]).
  16. -type constraint() :: int | nonempty | fun().
  17. -export_type([constraint/0]).
  18. -spec validate(binary(), [constraint()]) -> true | {true, any()} | false.
  19. validate(Value, [Constraint]) ->
  20. apply_constraint(Value, Constraint);
  21. validate(Value, Constraints) when is_list(Constraints) ->
  22. validate_list(Value, Constraints, original);
  23. validate(Value, Constraint) ->
  24. apply_constraint(Value, Constraint).
  25. validate_list(_, [], original) ->
  26. true;
  27. validate_list(Value, [], modified) ->
  28. {true, Value};
  29. validate_list(Value, [Constraint|Tail], State) ->
  30. case apply_constraint(Value, Constraint) of
  31. true ->
  32. validate_list(Value, Tail, State);
  33. {true, Value2} ->
  34. validate_list(Value2, Tail, modified);
  35. false ->
  36. false
  37. end.
  38. %% @todo {int, From, To}, etc.
  39. apply_constraint(Value, int) ->
  40. int(Value);
  41. apply_constraint(Value, nonempty) ->
  42. nonempty(Value);
  43. apply_constraint(Value, F) when is_function(F) ->
  44. F(Value).
  45. %% Constraint functions.
  46. int(Value) when is_binary(Value) ->
  47. try {true, list_to_integer(binary_to_list(Value))}
  48. catch _:_ -> false
  49. end.
  50. nonempty(<<>>) -> false;
  51. nonempty(Value) when is_binary(Value) -> true.