0

I what the idiomatic way of handling optional query parameters in Compojure and assign undefined query parameters to a default value.

I've tried this (which perhaps obviously doesn't work):

(GET "/something/:id" [id q :<< as-int :or {q (System/currentTimeMillis)}]
    ....)

I'd like this route to match both:

curl /something/123

and

curl /something/123?q=234542345

(Note a similar question has been posted here but it uses Swagger)

Community
  • 1
  • 1
Johan
  • 37,479
  • 32
  • 149
  • 237

1 Answers1

1

There are lots of options you could take. This is one I might choose.

(GET "/something/:id" req
  (let [{:keys [id q] :or {q (System/currentTimeMillis)}} (:params req)]

    ,,,))

Ultimately, though, which one I chose would depend on whatever led to the most readable (a subjective measurement, but that's the way it goes) code.

Russell
  • 12,261
  • 4
  • 52
  • 75
  • 2
    by the way, the reason I use commas instead of dots for the "ellipsis" is that they are interpreted as whitespace by the clojure compiler, so you can use them liberally for illustration purposes while the code remains compilable! I can't remember where I first saw this idea or I would credit it here, it's a really nice one, even though it looks weird at first. – Russell Sep 08 '16 at 22:24