Skip to content

Instantly share code, notes, and snippets.

@aroemers
Created November 2, 2016 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aroemers/47e5b1416421ea24998bfe06444da80f to your computer and use it in GitHub Desktop.
Save aroemers/47e5b1416421ea24998bfe06444da80f to your computer and use it in GitHub Desktop.
Stateful session in pedestal
(ns stateful-session
(:refer-clojure :exclude (get)))
(def ^:dynamic *session*)
(def stateful-session
{:name ::stateful-session
:enter
(fn [context]
(let [old-value (get-in context [:request :session] {})]
(-> context
(assoc ::session-old-value old-value)
(assoc-in [:bindings #'*session*] (atom old-value)))))
:leave
(fn [context]
(let [old-value (-> context ::session-old-value)
new-value (deref *session*)]
(if (not= old-value new-value)
(assoc-in context [:response :session] new-value)
context)))})
(defn get
"Get a key from the session."
([k]
(get k nil))
([k not-found]
(get (deref *session*) k not-found)))
(defn put!
"Set an entry in the session."
[k v]
(swap! *session* assoc k v))
(defn remove-session!
"Clear the session."
[]
(reset! *session* nil))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment