我有几个请求处理程序,它们都有相似的格式。
(defn handle-data-1
[req]
{:pre [(some? req)]}
(try
(let [start-date (parse-query-param (-> req :params :start-date))
end-date (parse-query-param (-> req :params :end-date))
data (db/fetch-data-1 start-date end-date)
data-count (count data)]
(log/debugf "data-count=%d start-date=%s end-date=%s" data-count start-date end-date)
(if (pos? data-count)
{:status 200
:body data}
{:status 404}))
(catch Exception e
(let [error-message (.getMessage e)]
(log/errorf "%s" error-message)
{:status 500 :body error-message}))))
(defn handle-data-2
[req]
{:pre [(some? req)]}
(try
(let [limit (Long/valueOf (parse-query-param (-> req :params :limit)))
data (db/fetch-data-2 limit)
data-count (count data)]
(if (pos? data-count)
{:status 200
:body data}
{:status 404}))
(catch Exception e
(let [error-message (.getMessage e)]
(log/errorf "%s" error-message)
{:status 500 :body error-message}))))
(defn handle-data-3
[_]
(try
(let [data (db/fetch-data-3)
data-count (count data)]
(log/debugf "data-count=%d" data-count)
(if (pos? data-count)
{:status 200
:body data}
{:status 404}))
(catch Exception e
(let [error-message (.getMessage e)]
(log/errorf "%s" error-message)
{:status 500 :body error-message}))))
我正在尝试创建一个通用函数,该函数可以被所有处理程序函数使用。类似于:
(defn try-query [f]
{:pre [(some? f)]}
(try
(let [data (f) ;; <- need to invoke function and store results in data
data-count (count data)]
(if (pos? data-count)
{:status 200
:body data}
{:status 404}))
(catch Exception e
(let [error-message (.getMessage e)]
(log/errorf "%s" error-message)
{:status 500 :body error-message}))))
(defn handle-data-1 [req]
(let [start-date (parse-query-param (-> req :params :start-date))
end-date (parse-query-param (-> req :params :end-date))]
(log/debugf "start-date=%s end-date=%s" start-date end-date)
(try-query (fn [] (db/fetch-data-1 start-date end-date))))) ;;
此通用函数需要以另一个函数(或闭包)作为参数,并且可以具有可变的参数数量。我希望这个通用函数可以调用传入的函数,并将结果存储在一个变量中。
在Ruby中,我可以通过向函数传递lambda函数来实现,然后在函数内部调用lambda函数。我不确定如何在Clojure中实现。
有什么想法吗?