我有几个请求处理器,它们都遵循相似的模式。
(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 中实现这一点。
有想法吗?