簡體   English   中英

Node.js / Express應用程序架構

[英]Node.js/Express application architecture

在PHP應用程序中,我可以創建類層次結構

class UserController  extends Controller {
    public function __constructor(){
        //..
    }
}

class LoggedUserController  extends UserController  {
    protected $_loggedUser;
    public function __constructor(){
        if( empty($_SESSION['user']) ){
            die('Access denied');
        }
        else{
            $this->_loggedUser = $_SESSION['user'];
        }
    }
}

class MessagesController  extends LoggedUserController {
    public function action_get_all(){
        // here I can use $this->_loggedUser and be sure that it is not empty
        //  Something like that:
        $messages = ORM::factory('messages')->where('user_id', '=', $this->_loggedUser->id)->find_all();
    }
}

以相同的方式,我可以創建AdminUserController類,並確保該控制器對非管理員用戶不可用。

但是在Node.js中,我無法使用此技巧,因為在加載應用程序時,僅會一次控制控件的構造函數。

也許有一些方法可以在Node.js中實現?

您可以使用CoffeeScript在NodeJS中實現類似的功能。 與使用純JavaScript相比,CoffeeScript允許您以一種更簡潔的方式創建類和其他構造。 盡管涉及學習曲線,但這可能是值得的。

就問題的第二部分而言,您將以不同的方式做同樣的事情。 您可以使用請求鏈來使用ExpressJS實現此目的。 例如,考慮以下(常規JavaScript方法):

app.requiresAdminUser = function(req, res, next) {
    if (req.session.user.role.indexOf('admin') > -1) return next();
    return res.send("Not Authorized", 401);
}

app.get('/site/public/page', function(req, res) {
    res.render('mypage');
});

app.get('/site/admin/secure', app.requiresAdminUser, function(req, res) {
    res.render('mysecurepage');
});

我相信代碼是不言自明的。 如果不清楚,請回答您的問題。

CoffeeScript可以使上面的代碼看起來更干凈。 同樣,當您進入功能完善的應用程序時,可以將此類代碼放入CoffeeScript類中,並在主應用程序文件中實例化它們,然后將方法傳遞到路由定義中。

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM