Skip to content

Component integration

Juho Teperi edited this page Dec 18, 2015 · 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:

Lexical bind with Components as a function arguments

(defn create-handler [{:keys [db] :as system}]
  (api
    (swagger-docs)
    (swagger-ui)
    (GET* "/user/:id" []
      :path-params [id :- s/Str]
      (ok (get-user db id)))))

Passing Components via request

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])

(defapi handler
  (GET* "/user/:id" []
    :path-params [id :- s/Str]
    :components [db]
    (ok (get-user db id))))

(defn app (mw/wrap-components handler (create-system))
(defapi app
  {:components (create-system)}
  (GET* "/user/:id" []
    :path-params [id :- s/Str]
    :components [db]
    (ok (get-user db id))))

To see this in action, try lein run and navigate to Components api group.

Clone this wiki locally