From 8228408082da5384a142c67b448dcfb01b45231c Mon Sep 17 00:00:00 2001 From: gered Date: Tue, 4 Jan 2022 19:20:17 -0500 Subject: [PATCH] delete-session now also calls on-expiry when it deletes something --- src/aging_session/core.clj | 10 +++++++++- test/aging_session/core_test.clj | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/aging_session/core.clj b/src/aging_session/core.clj index 60f48d8..f8c4c63 100644 --- a/src/aging_session/core.clj +++ b/src/aging_session/core.clj @@ -113,7 +113,15 @@ key)) (delete-session [_ key] - (swap! session-atom dissoc key) + (if on-expiry + ; if we have an on-expiry listener, we need to check if we actually removed the entry + ; and then call on-expiry + (let [[old new] (swap-vals! session-atom dissoc key)] + (if (and (contains? old key) + (not (contains? new key))) + (on-expiry key (-> old (get key) :value) :deleted))) + ; if there's no on-expiry listener, just do the delete + (swap! session-atom dissoc key)) nil)) (defn- sweeper-thread diff --git a/test/aging_session/core_test.clj b/test/aging_session/core_test.clj index 79da89f..70a483a 100644 --- a/test/aging_session/core_test.clj +++ b/test/aging_session/core_test.clj @@ -320,4 +320,20 @@ (is (>= keep-time-diff 800)))) (stop as))) +(deftest expiry-listener-triggered-when-delete-session-removes-entry + (let [expired (atom nil) + as (aging-memory-store 1 {:on-expiry #(reset! expired [%1 %2 %3])})] + (write-session as "foo" {:foo 1}) + (is (= (read-session as "foo") {:foo 1})) + (is (nil? @expired)) + (delete-session as "foo") + (is (= ["foo" {:foo 1} :deleted] @expired)) + (is (nil? (read-session as "foo"))))) + +(deftest expiry-listener-not-triggered-when-delete-session-called-for-non-existent-key + (let [expired (atom nil) + as (aging-memory-store 1 {:on-expiry #(reset! expired [%1 %2 %3])})] + (delete-session as "foo") + (is (nil? @expired)))) + #_(run-tests)