Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add docstrings to system.components.handler #103

Merged
merged 2 commits into from
Jan 15, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions src/system/components/handler.clj
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@
[lang-utils.core :refer [contains+? ∘]]
[compojure.core :as compojure]))

(defn- endpoints [component]
(defn- endpoints
"Find all endpoints this component depends on, returns map entries of the form
[name component]. An endpoint is a component that define a `:routes` key."
[component]
(filter (comp :routes val) component))

(defn- with-middleware
"Returns all endpoints that include middleware. With `flag` being false:
returns all enpoints that *don't* include middleware. Works on [name
component] map entry pairs."
([endpoints]
(with-middleware endpoints true))
([endpoints flag]
Expand All @@ -15,7 +21,10 @@
(fn [[k v]] (not (contains+? v :middleware))))]
(filter f endpoints))))

(defn- middleware-key [endpoint]
(defn- middleware-key
"Given the endpoint map-entry this returns the key of the
middleware dependency if any, or an empty map."
[endpoint]
(reduce-kv (fn [_ k v] (if (contains+? v :middleware) (reduced k) _)) {} (val endpoint)))

(defrecord Handler []
Expand All @@ -37,4 +46,29 @@
(dissoc component :handler)))

(defn new-handler
"Creates a handler component. A handler component combines endpoints and
middleware into a ring handler function.

Endpoints should be added as dependencies using `component/using`, the names
used for endpoints don't matter, they are recognized by their structure.

Middleware can be added by depending on a middleware component, either
per-endpoint, or once for the complete handler. Per-endpoint middleware can
use any name, middleware on the handler must be called `:middleware`.

The resulting ring handler function is available as `:handler` on the handler
component.

Example:

(component/system-map
:endpoint-a (new-endpoint some-routes)
:endpoint-b (-> (new-endpoint other-routes)
(component/using [:endpoint-b-middleware]))
:endpoint-b-middleware (new-middleware {:middleware [,,,]})
:middleware (new-middleware {:middleware [,,,]})
:handler (-> (new-handler)
(component/using [:endpoint-a :endpoint-b :middleware]))
:jetty (-> (new-web-server port)
(component/using [:handler])))"
([] (->Handler)))