Fork me on GitHub
#malli
<
2022-01-13
>
Mutasem Hidmi06:01:01

Hi guys, how are you? I am new to Clojure. I wanted to ask a question about humanizing the errors returned from Malli when used as coercion. I tried to do like below, but it didn't work.

(def custom-coercion (reitit.coercion.malli/create
               {:transformers {:body {:default reitit.coercion.malli/default-transformer-provider
                                      :formats {"application/json" reitit.coercion.malli/json-transformer-provider}}
                               :string {:default reitit.coercion.malli/string-transformer-provider}
                               :response {:default reitit.coercion.malli/default-transformer-provider}}
                :error-keys #{:type :coercion :in :schema :value :errors :humanized #_:transformed}
                :compile mu/closed-schema
                :encode-error (fn [error] {:errors (:humanized error)})
                :validate true
                :enabled true
                :strip-extra-keys true
                :default-values true
                :options nil}))

dharrigan06:01:58

I have an example

dharrigan06:01:03

give me a moment and I'll push it up to github

Mutasem Hidmi06:01:02

Thank @dharrigan. I appreciate it.

dharrigan06:01:46

Here you go:

dharrigan06:01:59

It's a very simple example, which may help you along the path

dharrigan06:01:18

In particular, look at:

dharrigan06:01:52

And here is the malli spec for the API:

dharrigan06:01:08

The encode-error function can be certainly improved (it assumes only one error, there could be multiple). Treat it like a starting point 😉

dharrigan06:01:45

Here is an example of a failure response:

dharrigan06:01:47

❯ http :8080/api/foo      
HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked

What is going on?? There is a 'missing required key'. I was expecting a value for '[:id]' but got 'null' instead!

dharrigan06:01:55

and here is an example of a successful response:

dharrigan06:01:01

❯ http :8080/api/foo?id=10
HTTP/1.1 200 OK
Content-Length: 14
Content-Type: application/json;charset=utf-8

{
    "hello": "10"
}

Mutasem Hidmi06:01:06

Thank you. I am checking it now

Mutasem Hidmi08:01:44

Thanks buddy. By the way, you can put also this :error-keys #{:type :coercion :in :schema :value :errors :humanized #_:transformed} in order to get a humanized key that you can use in the encode-error