-
Notifications
You must be signed in to change notification settings - Fork 149
Component integration
Tommi Reiman edited this page Feb 9, 2016
·
2 revisions
Stuert Sierra's Component is a great library for managing the stateful resources of your app. There are several strategies to use it. Here are some samples how to use Component with compojure-api:
This is the preferred way as we are not littering the request.
(defn more-routes [db]
(routes
(GET "/ping" []
(ok {:ping (str "I have a db: " db)}))))
(defn create [{:keys [db] :as system}]
(api
(GET "/user/:id" []
:path-params [id :- s/Str]
(ok (get-user db id))
(more-routes db))))
Use either :components
-option of api-middleware
or wrap-components
-middleware
to associate the components with your API.
Components can be read from the request using compojure.api.middleware/get-components
or using
the :components
restucturing with letk-syntax.
(require '[compojure.api.middleware :as mw])
(defroutes more-routes
(GET "/ping" []
:components [db]
(ok {:ping (str "I have a db: " db)})))
(defapi handler
(GET "/user/:id" []
:path-params [id :- s/Str]
:components [db]
(ok (get-user db id)))
more-routes)
(defn app (mw/wrap-components handler (create-system))
(defroutes more-routes
(GET "/ping" []
:components [db]
(ok {:ping (str "I have a db: " db)})))
(defapi app
{:components (create-system)}
(GET "/user/:id" []
:path-params [id :- s/Str]
:components [db]
(ok (get-user db id)))
more-routes)
To see this in action, try lein run
and navigate to Components api group.