Passing state as parameter to a ring handler?

前端 未结 3 564
渐次进展
渐次进展 2021-01-02 00:24

How does one inject state into ring handlers most conveniently (without using global vars)?

Here is an example:

(defroutes main-routes
  (GET \"/api/         


        
3条回答
  •  青春惊慌失措
    2021-01-02 00:57

    In addition to what Alex described some routing frameworks for ring have a place for additional arguments which can be accessed by all handlers. In reitit this would work by putting custom objects under :data:

     (reiti.ring/ring-handler
       (reiti.ring/router
        [ ["/api"
          ["/math" {:get {:parameters {:query {:x int?, :y int?}}
                          :responses  {200 {:body {:total pos-int?}}}
                          :handler    (fn [{{{:keys [x y]} :query} :parameters}]
                                        {:status 200
                                         :body   {:total (+ x y)}})}}]] ]
        {:syntax    :bracket
         :exception pretty/exception
         :data      {:your-custom-data your-custom-data
                     :coercion   reitit.coercion.spec/coercion
                     :muuntaja   m/instance
                     :middleware []}}))
    

    In your handler you're supposed to only work with :parameters, but you will be able to access your custom data by selecting :reitit.core/match and :data. The argument that the handler receives is based entirely on this:

    (defrecord Match [template data result path-params path])
    (defrecord PartialMatch [template data result path-params required])
    

提交回复
热议问题