Created
November 2, 2016 12:32
-
-
Save aroemers/47e5b1416421ea24998bfe06444da80f to your computer and use it in GitHub Desktop.
Stateful session in pedestal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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