将状态作为参数传递给环处理程序? [英] Passing state as parameter to a ring handler?

查看:131
本文介绍了将状态作为参数传递给环处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



下面是一个例子:

 (defroutes main-routes 
(GET/ api / fu[](rest-of-the-app the-state)))

(def app
( - >(handler / api main-routes)))

我想得到 the-state main-routes 的compojure处理程序。状态可能类似于使用以下创建的映射:

 (defn create-app-state [] 
{ db(connect-to-db)
:log(create-log)})

在非环应用中,我将在主函数中创建状态,并开始将它或其部分注入作为应用程序的不同组件的函数参数。



可以使用ring的:init 函数而不使用全局变量来完成类似的操作。

解决方案

我看到这样做了几个方法。第一种是使用中间件,将状态作为新的键注入请求映射中。例如:

 (defroutes main-routes 
(GET/ api / fu[:as request]
(rest-of-the-app(:app-state request))))

(defn app-middleware [f state]
(fn [request]
(f(assoc request:app-state state))))

(def app
( - > main-routes
状态))
handler / api))

另一种方法是将调用 defroutes ,在后台将创建一个处理程序并将其分配给一个var,一个函数将接受一些状态,然后创建路由,注入状态作为参数函数调用的路由定义:

 (defn app-routes [the-state] 
(compojure.core / route
(GET/ api / fu[](rest-of-the-app the-state))))

(def app
( - > create-app-state)
app-routes
api / handler))

给定一个选择,我可能会采用第二种方法。


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

Here is an example:

(defroutes main-routes
  (GET "/api/fu" [] (rest-of-the-app the-state)))

(def app
  (-> (handler/api main-routes)))

I would like to get the-state into the compojure handler for main-routes. The state might be something like a map created with:

(defn create-app-state []
  {:db (connect-to-db)
   :log (create-log)})

In a non ring application I would create the state in a main function and start injecting it, or parts of it, as function parameters to the different components of the application.

Can something similar be done with ring's :init function without using a global var?

解决方案

I've seen this done a couple of ways. The first is using middleware that injects the state as a new key in the request map. For instance:

(defroutes main-routes
  (GET "/api/fu" [:as request]
    (rest-of-the-app (:app-state request))))

(defn app-middleware [f state]
  (fn [request]
    (f (assoc request :app-state state))))

(def app
  (-> main-routes
      (app-middleware (create-app-state))
      handler/api))

The other approach is to replace the call to defroutes, which behind the scenes will create a handler and assign it to a var, with a function that will accept some state and then create the routes, injecting the state as parameters to function calls within the route definitions:

(defn app-routes [the-state]
  (compojure.core/routes
    (GET "/api/fu" [] (rest-of-the-app the-state))))

(def app
  (-> (create-app-state)
      app-routes
      api/handler))

Given a choice, I'd probably go with the second approach.

这篇关于将状态作为参数传递给环处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆