对于这个简单的逻辑,什么是惯用的Clojure?

时间:2013-11-30 12:44:31

标签: clojure idiomatic

我在Clojure中编写了一个简单的设计auth函数,它对我来说根本不是很惯用。有没有更好的方式来写这个:

(defn auth [username password] 
  (let [user-record (credential-fn username)]
    (if (and user-record (verify-pw password))
      (let [user-record (dissoc user-record :password)]
        {:status 200 :body user-record})
      {:status 401})))

我认为可以使用if删除if-let,但if正在进行布尔检查,我需要绑定user-record ?卡住!

注意:dissoc正在从user-record中删除密码,因此密码不会在正文中返回。

1 个答案:

答案 0 :(得分:9)

我认为你的功能最大的问题是它试图同时处理三件事:

  1. 检查用户名和密码是否对用户有效(credential-fnverify-pw
  2. 清理记录数据(dissoc user-record password)
  3. 制作响铃响应地图({:status 401}{:status 200 :body user-record}
  4. 我会考虑将您的代码拆分为两个独立的函数:

    (defn authenticate
      [username password]
      (and (verify-pw password) 
           (dissoc (credential-fn username) :password)))
    
    (defn login
      [username password]
      (if-let [user-record (authenticate username password)]
        {:status 200 :body user-record}
        {:status 401}))