2013-10-30 31 views

回答

3

即使它的一個老問題,這裏是我的答案。問題是從請求中獲取當前用戶進入鉤子狀態。這些步驟可能使你得到的是:

  1. 創建自定義查詢功能的中間件
     
    req.context.findById = function(model){ 
        // Strip model from arguments 
        Array.prototype.shift.apply(arguments); 
        // Apply original function 
        return model.findById.apply(model, arguments).then(function(result){ 
        result.context = { 
         user: req.user 
        } 
        return result; 
        }); 
    }; 
    
  2. 不要使用req.findById(model, id)代替User.findById(id)
     
    app.put("/api/user/:id", app.isAuthenticated, function (req, res, next) { 
        // Here is the important part, user req.context.findById(model, id) instead of model.findById(id) 
        req.context.findById(User, req.params.id).then(function(item){ 
         // item.context.user is now req.user 
         if(!user){ 
         return next(new Error("User with id " + id + " not found")); 
         } 
         user.updateAttributes(req.body).then(function(user) { 
         res.json(user); 
         }).catch(next); 
        }).catch(next); 
    }); 
    
  3. 用你的鉤子上放,instance.context.user將可
     
    User.addHook("afterUpdate", function(instance){ 
        if(instance.context && instance.context.user){ 
         console.log("A user was changed by " + instance.context.user.id); 
        } 
    }); 
    

你可以在這裏找到這個程序解壓到一個express expressware https://github.com/bkniffler/express-sequelize-user(我是創建者)。

0

如果有用戶和車輛之間的一個一對多的關係,如果車輛的實例已與用戶相關聯,那麼你可以使用vehicle.getUser()。

... 
beforeUpdate: function(vehicle,cb){ 
    vehicle.getUser() 
    .then(function(user){ 
    console.log(user) 
    }) 
} 

如果車輛屬性之一是uid。

beforeUpdate: function(vehicle,cb){ 
    User.find(vehicle.uid) 
    .then(function(user){ 
    console.log(user) 
    }) 
} 

否則,這將不得不在控制器中完成。有沒有在控制器中處理這個問題的好理由?在Vehicle上創建一個名爲logUser()的類方法,它接受req.user似乎是阻力最小的路徑。

+0

接受,即使是棘手的問題被問*去年*,它並沒有真正回答這個問題。 – jValdron

相關問題