Fork me on GitHub
#reitit
<
2021-04-20
>
ben74113:04:42

Hi, I might be missing something obvious, but how can I make query parameters optional in reitit.coercion.spec/coercion? i.e. I'd like to accept both requests to /images but also /images?subject=cat . Something like :query {:subject (s/nilable string?)} still just gives a 400 bad request because :subject is a required key.

ben74113:04:19

Ah, I had to use spec-tools.data-spec and :query {(ds/opt :subject) string?}

Toni Vanhala14:04:39

I think you could use :req-un and :opt-un keys with spec coercion

athomasoriginal15:04:41

^^ Indeed. It wasn’t immediately intuitive to me either, but this works

(s/def ::param boolean?)

(s/def ::optional-params
  (s/keys :opt-un [::param]))

["/your-route"
  {:name :blah
   :parameters {:query ::optional-params}}]

"/your-route?param=true"

ben74120:04:16

From the Reitit source it looks like that should work, but it doesn't for me for some reason. Anyways, it also looks like directly using a spec there would let in any other unexpected params without coercing them, which isn't necessarily what I want.