Question

I want different handlers to set different keys in the session without affecting each other. I'm working from this wiki article, which advises using assoc. I thought I could use assoc-in to update a path in the session.

(defn handler-one
  [request]
  (prn "Session before one" (:session request))
  (-> (response "ONE")
          (content-type "text/plain")
          (#(assoc-in % [:session :key-one] "one"))))

(defn handler-two
  [request]
  (prn "Session before two" (:session request))
  (-> (response "TWO")
          (content-type "text/plain")
          (#(assoc-in % [:session :key-two] "two"))))

If I call handler-one repeatedly it prints Session before one {:key-one "one"} and likewise handler-two prints the previous session values.

By setting a session key using assoc-in I would expect both keys to be set, i.e. {:key-one "one" :key-two "two"}. But it appears that the entire session dictionary is replaced.

Am I doing this wrong?

Was it helpful?

Solution

You're printing the session in request, but you're assoc'ing on the (nonexistent) session in response so you end up with a session with only the last added property. You should get the session out of request, assoc into that and then return the new session as part of the response.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top