From 51cfc819be07922236923108e7c0892d2fcf7304 Mon Sep 17 00:00:00 2001 From: Mikhail Kuzmin Date: Wed, 16 Oct 2024 21:17:13 +0400 Subject: [PATCH] Add log middleware --- src/darkleaf/di/core.clj | 16 ++++++++++ test/darkleaf/di/tutorial/x_log_test.clj | 37 ++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 test/darkleaf/di/tutorial/x_log_test.clj diff --git a/src/darkleaf/di/core.clj b/src/darkleaf/di/core.clj index 58c0018a..cb8f4c6f 100644 --- a/src/darkleaf/di/core.clj +++ b/src/darkleaf/di/core.clj @@ -784,3 +784,19 @@ ~@body)) (finally (.close resource#))))))) + +(defn log [built-cb demolished-cb] + (fn [registry] + (fn [key] + (let [factory (registry key)] + (reify p/Factory + (dependencies [_] + (p/dependencies factory)) + (build [_ deps] + (let [obj (p/build factory deps)] + (built-cb key deps obj) + obj)) + (demolish [_ obj] + (p/demolish factory obj) + (demolished-cb key obj) + nil)))))) diff --git a/test/darkleaf/di/tutorial/x_log_test.clj b/test/darkleaf/di/tutorial/x_log_test.clj new file mode 100644 index 00000000..938aa8ce --- /dev/null +++ b/test/darkleaf/di/tutorial/x_log_test.clj @@ -0,0 +1,37 @@ +(ns darkleaf.di.tutorial.x-log-test + (:require + [clojure.test :as t] + [darkleaf.di.core :as di])) + +(defn a + {::di/kind :component} + [] + :a) + +(defn b [{a `a}] + :b) + +(defn c + {::di/kind :component} + [{b `b}] + :c) + +(t/deftest log + (let [logs (atom []) + built! (fn [key deps obj] + (swap! logs conj [:built key deps obj])) + demolished! (fn [key obj] + (swap! logs conj [:demolished key obj])) + [a b c + :as system] (di/start [`a `b `c] + (di/log built! demolished!))] + (di/stop system) + (t/is (= [[:built `a {} a] + [:built `b {`a a} b] + [:built `c {`b b} c] + [:built ::di/implicit-root {`a a `b b `c c} [a b c]] + [:demolished ::di/implicit-root [a b c]] + [:demolished `c c] + [:demolished `b b] + [:demolished `a a]] + @logs))))