Skip to content

Populate default values for optional keys in query parameters #750

@dzhus

Description

@dzhus

If the schema of :query parameters is a :map with {:optional keys that have default values set for them, there seems to be no way to enable add-optional-keys option for the default-value-transformer in the default chain.
This means there's no way to both use reitit coercion, have optional query parameters, and also populate default values for them (+ communicate those defaults via OpenAPI spec).

Is this by design/intentional?

As an example, a failing test is something like this:

(testing "default values for optional query params missing from request"
    (let [router (r/router ["/test"
                            {:name ::route
                             :coercion reitit.coercion.malli/coercion
                             :parameters {:query [:map
                                                  [:x {:optional true} ;;;; !!!!!
                                                   [:keyword {:default :a}]]]}}] ;;;;; <<<<<<
                           {:compile coercion/compile-request-coercers})]
      (is (= {:query {:x :a}}
             (-> (r/match-by-path router "/test")
                 (assoc :query-params {})
                 (coercion/coerce!))))))

Which as seen here fails with

FAIL in reitit.coercion-test/match->path-parameter-coercion-test (coercion_test.cljc:233)
default values for optional query params missing from request
expected: {:query {:x :a}}
  actual: {:query {}}

It seems to be fixable via custom middleware / coercion but I wonder if there'd be an issue with simply threading through options from :coercion to the default-value-transformer, which would then allow the API user to enable population of optional keys?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions