jonasschmidt / ex_json_schema

An Elixir JSON Schema validator
MIT License
366 stars 98 forks source link

validation errors with format #38

Closed albertored closed 5 years ago

albertored commented 6 years ago

Hi, I took your validatio-errors branch, added the missing format part, rebased on current master and fixed some dialyzer warnings.

For the formatting part I added a new module (ExJsonSchema.ErrorFormatter) exposing a function format/{1,2} that takes the output of ExJsonSchema.Validator.validate/{2,3} and an optional keyword and formats the errors.

When calling it without options the output format is the legacy one ([{msg :: String.t(), path :: String.t()}].

If called with [output: :json] as second argument the output is a "json-friendly" map that can be returned for instance in a body of a HTTP response. Something like

%{
  "a" => %{
    "oneOf" => %{
      "0" => %{"errors" => ["Required properties p1,p2 were not present"]},
      "1" => %{
        "p4" => %{
          "anyOf" => %{
            "0" => %{"errors" => ["Required property p5 was not present"]},
            "1" => %{"errors" => ["Required property p6 was not present"]}
          }
        }
      }
    }
  },
  "b" => %{"errors" => ["Expected value to be >= 100"]},
  "errors" => ["Required property c was not present"]
}

We can also move the :output option in the validate method having the result to be in the legacy format by default and adding a third option (maybe :bare) to return the complex error struct.

I would like to know your opinion, then, if you agree I can add some test and merge it.

albertored commented 6 years ago

whoops... just notice the other PR (#27) that address the same issue (#22)... sorry about that..

jonasschmidt commented 6 years ago

Sorry for the delay, I only found the time today to look into this. Thanks a lot for investing the time to come up with a solution. I like the approach in general that by default it returns the legacy format. If it's possible to keep backward compatibility without compromising the API design too much then it's worth doing that. I will have a look today to see how we can finally get this merged and released.

albertored commented 6 years ago

No problem, let me know if I can help somehow

jonasschmidt commented 5 years ago

I finally managed to release those changes in 0.6.0. The README has some examples of how to use it. In the end I decided to keep backward compatibility and haven an option to disable the formatting (or provide a custom one). Thank you again for the help on this improvement.