DEV Community

Cover image for Clojure Is Awesome!!! [PART 4]
André Borba
André Borba

Posted on • Edited on

Clojure Is Awesome!!! [PART 4]

(ns monostate) (def ^:private session-state (atom {:user-id nil :permissions #{} :last-access nil})) (defn start-session "Starts a new user session with ID and permissions." [user-id permissions] (reset! session-state {:user-id user-id :permissions permissions :last-access (java.time.Instant/now)})) (defn end-session "Ends the session, resetting the state to default values." [] (reset! session-state {:user-id nil :permissions #{} :last-access nil})) (defn update-last-access "Updates the last access timestamp to the current time." [] (swap! session-state assoc :last-access (java.time.Instant/now))) (defn get-session "Retrieves the complete state of the current session." [] @session-state) (defn has-permission? "Checks if the user has a specific permission." [permission] (contains? (:permissions @session-state) permission)) (comment (start-session "user-123" #{"read" "write"}) ;; => {:user-id "user-123", :permissions #{"read" "write"}, :last-access <timestamp>} (has-permission? "read") ;; => true (has-permission? "delete") ;; => false (update-last-access) (get-session) ;; => {:user-id "user-123", :permissions #{"read" "write"}, :last-access <new-timestamp>} (end-session) ;; => {:user-id nil, :permissions #{}, :last-access nil} ) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)