Nanit Engineering Blog - Writing an elixir plug library



Might be a good idea to rename your library to something like PlugValidator since Plug namespace should belong to plug.

A validation function should return {:error, the_error} in case of failed validation. Any other value returned indicates the validation has passed. This is to follow a common Elixir convention in return values.

~~ Why not halt/1 the request with plug instead of returning {:error, the_errors} which, I suppose, you handle some time later (in &on_error_fn/2)? ~~

Ah, I see now, you want collect all validation errors.

If you do decide to enforce {:error, the_errors}, then, as extra documentation, you can add a @behaviour for it with callbacks specifying the return type.

defmodule PlugValidator.Validation do
  @callback validate(validation_name :: atom, validated_value :: term) :: {:ok, term} | {:error, description :: String.t()}

Thanks for the feedback I appreciate it. Some answers to your questions/suggestions:

  1. I mentioned in the last words that only after writing and publishing the library I found out that I’d better name the module PlugValidator rather than Plug.Validator.
  2. The idea was to let the users handle the errors how they like to. What if some errors can be recovered from? Also I wanted to collect all invalid parameters if I’d halt the Plug on the first error I encounter this would not be possible
  3. I agree that I’m missing specs in the library. I intend to learn more about it and add it to the module.