Fork me on GitHub
#mount
<
2022-11-08
>
Daniel Shriki16:11:03

Hi, I’m using a middleware to insert db state which is loaded using mount. the problem is that the middleware is been running before the db is initialized, and when I’m trying to use it I’m getting uninitialized state. this is how the middleware looks like:

(defn wrap-state [handler]
  (let [state {:ds         @db/ds}]
    (cw/wrap-state handler state)))
But if I’m using deref only in the designated function that use that eventually using it (instead of in the middleware) it’s working. anyone know why? can it be solved?

tolitius20:11:02

two thougts: 1 > the middleware is been running before the db is initialized usually a server would depend on the middleware (same namespace or required) in which case it (middleware) would require a database namespace which would, in this case be compiled first on (mount/start) the database would start first, since it was the first one to compile, hence mount would record it in such order: before the server / middleware 2 would recommend not to close over state: i.e. functions should take it vs. close over it:

(defn wrap-state [db handler]
  (let [state {:ds         (:ds db)}]
    (cw/wrap-state handler state)))

Daniel Shriki10:11:09

can you explain what you mean by ‘close over state’? db in that case is just ns, not an object

Daniel Shriki11:11:22

I would think the same, but practically I’m logging when both things are happening, and I see clearly that the db is initialized after. also, when I’m actually using the db, I’m getting an error that the connection is empty (aka not initialized)

tolitius16:11:35

> can you explain what you mean by ‘close over state’ sure

(defn closing-over [a b]
  (store db a b))
vs.
(defn not-closing-over [db a b]
  (store db a b))
the closing-over is a stateful function that closes over the “db” state / coupled to the “`db`” state vs. the not-closing-over is a stateless function that takes this state (“`db`”) as an argument there are multiple advantages not to close over: testing, concurrency, debugging, REPLing, reusing, composing, etc.. > practically I’m logging when both things are happening if an http server requires db, the db will be started before the server in order to understand how your code is structured, you can create a small repo to reproduce it and I can look at it