2017-08-06 43 views
1

rooms.js - >控制器類客房端點什麼可以是一個更好的方式來處理從nodejs項目中的控制器發送響應?

router.get('/:roomid/fight/verify', function(req, res) { 
     roomModel.authenticateUserForFight(req.params.roomid, req.query.otp, res); 
    }); 

roomModel - >的房間模型類

//authenticate user based on otp provided on client side 
exports.authenticateUserForFight = function(roomid, otp, res) { 
    db.query('select * from room where roomid=?', [roomid], function(error, rows) { 
    if (rows.length == 0) { 
     console.log("otp does not exist in db for room:" + roomid); 
    } else if (rows.length == 1) { 
     var otpInDb = rows[0].otp.toString(); 
     if (otp == otpInDb) { 
     console.log("User is authorised"); 
     res.status(200); 
     res.send("User is authorised"); 
     } else { 
     console.log("User is unauthorised"); 
     res.status(401); 
     res.send("User not authorised"); 
     } 
    } 
    }); 
} 

這段代碼工作正常,但有沒有更好的方式來發送響應客戶端而不是將res對象傳遞給模型類並在那裏設置狀態和響應消息?我傳遞res對象的原因是因爲在控制器中執行res.status和res.send會導致問題,因爲db調用是異步的。建議一些更好的做法來處理這種情況。

回答

1

您是對的。您不應該通過res對象。它是一個調試噩夢,如果有多個地方可以退出功能。後面的函數返回值並且控制器響應狀態要好得多。

您可以簡單地創建一個回調方法,一旦完成異步數據庫查詢,就會調用該方法。這樣

router.get('/:roomid/fight/verify', function(req, res) { 
     const callback = (status, message) => { 
     res.status = status 
     res.send(message); 
     } 
     roomModel.authenticateUserForFight(req.params.roomid, req.query.otp, callback); 
    }); 

和主要功能的東西可以直接調用這個函數

//authenticate user based on otp provided on client side 
exports.authenticateUserForFight = function(roomid, otp, callback) { 
    db.query('select * from room where roomid=?', [roomid], function(error, rows) { 
    if (rows.length == 0) { 
     console.log("otp does not exist in db for room:" + roomid); 
    } else if (rows.length == 1) { 
     var otpInDb = rows[0].otp.toString(); 
     if (otp == otpInDb) { 
     console.log("User is authorised"); 
     callback(200, 'user authorized'); 
     } else { 
     console.log("User is unauthorised"); 
     callback(401, 'user not authorized'); 

     } 
    } 
    }); 
} 
+0

謝謝。感謝幫助 – madcolonel10

1

這是更新的代碼

if (otp == otpInDb) { 
     console.log("User is authorised"); 
     res.json({ 
       status:200, 
       message:"user authorized" 
     }) 
     } else { 
     res.json({ 
       status:401, 
       message:"user not authorized" 
     }) 
     } 

它始終是不如送信封你的迴應。我可以看到你正在使用String類似的查詢。使用orm wrapper(如sequelize)來防止SQL注入攻擊

+0

目前,我與返回的從模型文件的響應。是否有可能以某種方式將其移到控制器類?你認爲從模特回來可以接受嗎? – madcolonel10

+0

根據我的偏好,我不會從模型文件返回。因爲模型定義了你的模式,它應該只有模式沒有別的 –

+0

你可以建議一些替代方法來從控制器文件返回這個。我無法從控制器返回,因爲db.query是異步調用,不會等待並將控制權交還給控制器。 – madcolonel10

相關問題