Merge pull request #584 from metosin/reloading-ring-handler

reloading-ring-handler
This commit is contained in:
Ilmo Raunio 2023-02-21 14:42:33 +02:00 committed by GitHub
commit e490f5df05
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 3 deletions

View file

@ -339,6 +339,22 @@
nil)))
{::r/router router}))))
(defn reloading-ring-handler
"Returns a ring-handler that recreates the actual ring-handler for each request.
Takes a 0-arity function that should return a valid ring-handler. Effectively creates
an auto-reloading ring-handler, which is good for REPL-driven development.
Example:
;; for dev-mode, recreate the ring-handler for each request, for prod, just once
(let [dev-mode ...
f (fn [] (reitit.ring/ring-handler ...)]
(if dev-mode (reitit.ring/reloading-ring-handler f) (f)))"
[f]
(fn
([request] ((f) request))
([request respond raise] ((f) request respond raise))))
(defn get-router [handler]
(-> handler meta ::r/router))

View file

@ -733,6 +733,25 @@
{::trie/trie-compiler compiler})]
(dotimes [_ 10]
(future
(dotimes [n 100000]
(let [body (:body (app {:request-method :get, :uri (str "/" n)}))]
(is (= body (str n))))))))))))
(dotimes [n 100000]
(let [body (:body (app {:request-method :get, :uri (str "/" n)}))]
(is (= body (str n))))))))))))
(declare routes)
(deftest reloading-ring-handler-test
(let [r (fn [body] {:status 200, :body body})]
(def routes ["/" (constantly (r "1"))]) ;; initial value
(let [create-handler (fn [] (ring/ring-handler (ring/router routes)))]
(testing "static ring handler does not see underlying route changes"
(let [app (create-handler)]
(is (= (r "1") (app {:uri "/", :request-method :get})))
(def routes ["/" (constantly (r "2"))]) ;; redefine
(is (= (r "1") (app {:uri "/", :request-method :get})))))
(testing "reloading ring handler sees underlying route changes"
(let [app (ring/reloading-ring-handler create-handler)]
(is (= (r "2") (app {:uri "/", :request-method :get})))
(def routes ["/" (constantly (r "3"))]) ;; redefine again
(is (= (r "3") (app {:uri "/", :request-method :get}))))))))