2014-02-28 90 views
0

我目前正在參與一個涉及使用Geddy js框架的項目,這是我第一次使用。我目前正在嘗試修復用戶模型中的創建方法。這是下面的代碼:Geddy保存用戶

this.create = function (req, resp, params) { 
    var self = this 
     , user = geddy.model.User.create(params); 

    //need to ensure that the user agrees with the terms and conditions. 

    // Non-blocking uniqueness checks are hard 
    geddy.model.User.first({username: user.username}, function(err, data) { 
     if (data) { 
     params.errors = { 
      username: 'This username is already in use.' 
     }; 
     //self.transfer('add'); 
     } 
     else { 
     if (user.isValid()) { 
      user.password = cryptPass(user.password); 
      user.suburb = ""; 
      user.state = ""; 
      user.postcode = ""; 
     } 
     user.save(function(err, data) { 
      if (err) { 
      params.errors = err; 
      self.transfer('add'); 
      } 
      else { 
       // setup e-mail data with unicode symbols 
       var mailOptions = { 
        from: "App ✔ <[email protected]>", // sender address 
        to: user.email, // list of receivers 
        subject: user.username + " Thank you for Signing Up ✔", // Subject line 
        text: "Please log in and start shopping! ✔", // plaintext body 
        html: "<b>Please log in and start shopping!✔</b>" // html body 
       } 

       smtpTransport.sendMail(mailOptions, function(error, response){ 
        if(error){ 
         console.log(error); 
        }else{ 
         console.log("Message sent: " + response.message); 
        } 

        // if you don't want to use this transport object anymore, uncomment following line 
        smtpTransport.close(); // shut down the connection pool, no more messages 
       }); 
      self.redirect({controller: self.name}); 
      } 
     }); 
     } 
    }); 
}; 

如果你在代碼看起來顯然有一個檢查,看看所謂的用戶是有效的,像這樣:if (user.isValid()) { user.password = cryptPass(user.password); user.suburb = ""; user.state = ""; user.postcode = ""; }

上「拯救」的收益,無論無論用戶是否有效。我在想爲什麼這樣的代碼?這聽起來毫無意義。我問了項目中的原始開發人員,他說這個模型顯然是在他創建項目時生成的。

因此,在困惑的狀態下,如果有人能告訴我爲什麼save方法在if語句之外? Geddy的原始創作者是否打算這麼做?或者是真的無意義,我應該改變它?

謝謝。

+0

user.isValid是做什麼用的?它可能會在返回錯誤之前設置'user.save'評估的屬性。或者可以通過設計來保存它。當然,看起來很奇怪,但它對於有效和無效的用戶是否按預期工作? –

+0

顯然它是Geddy的驗證模型及其屬性的方法 – koramaiku

+0

對不起,我對geddy並不熟悉,但是看起來好像用戶無效時會返回錯誤。 –

回答

0

Geddy's save()如果數據無效(除非設置了強制標誌,則不會調用)。它實際上使用相同的isValid()調用。因此,看起來你在這裏只是某人爲所有錯誤情況提供單一錯誤處理程序的方法。

對於user.password設置加密數據只有當數據看起來有效,我猜這只是爲了使'必須設置'的驗證類型工作。有機會,即使用空密碼,加密的字符串將被計爲集合。