2

在我的项目中,我有几个如下所示的类:

"use strict";
var exports = module.exports = {};
var SystemsDAO = require('./dao/systems/SystemsDAO.js');
var aop = require('./dbAOPUtils.js');
var Proxy = require('harmony-proxy');
var sqlite3 = require('sqlite3').verbose();

/* Wraps a SystemServiceObject and passes in a constructed
 * DAO object as an argument to specified functions. */
exports.SystemsDAOIntercepter = function(obj) {

    let handler = {
        get(target, propKey, receiver) {
           const origMethod = target[propKey];
           return function(...args) {
            console.log('systemDAOIntercepter: BEGIN');

            // Create a reportsdao object and proxy it through an dbSQLiteConnectionIntercepter
            // (So we don't have to create it for every single method) 
            var systemdao = new SystemsDAO('blah');
            var proxSystemDAO = aop.dbSQLiteConnectionIntercepter(systemdao, sqlite3.OPEN_READONLY);

            args.push(proxSystemDAO);

            console.log('propKey: ' + target[propKey]);

            let result = null;

            result = origMethod.apply(this, args);

            console.log('systemsDAOIntercepter: END');
            return result;
           };
        }
    };

    return new Proxy(obj, handler);
};

是否可以为参数传递一个类型,以便我只需要一个 DAOIntercepter 类,而不是每个数据访问对象一个?

通过传递文件名,我可以看到我为此工作的部分require()SystemsDAO但至于该类的实例化,我真的看不出如何做到这一点。

4

1 回答 1

2

当然——你可以像 javascript 中的任何其他变量一样传递类。

请注意DAOType,现在在方法内部提供并实例化了。

"use strict";
var exports = module.exports = {};
var aop = require('./dbAOPUtils.js');
var Proxy = require('harmony-proxy');
var sqlite3 = require('sqlite3').verbose();

/* Wraps a SystemServiceObject and passes in a constructed
 * DAO object as an argument to specified functions. */
exports.makeInterceptor = function(DAOType, obj) {

    let handler = {
        get(target, propKey, receiver) {
           const origMethod = target[propKey];
           return function(...args) {
            console.log('systemDAOIntercepter: BEGIN');

            // Create a reportsdao object and proxy it through an dbSQLiteConnectionIntercepter
            // (So we don't have to create it for every single method) 
            var dao = new DAOType('blah');
            var proxSystemDAO = aop.dbSQLiteConnectionIntercepter(dao, sqlite3.OPEN_READONLY);

            args.push(proxSystemDAO);

            console.log('propKey: ' + target[propKey]);

            let result = null;

            result = origMethod.apply(this, args);

            console.log('makeInterceptor: END');
            return result;
           };
        }
    };

    return new Proxy(obj, handler);
};

我不得不承认,我(个人)更愿意看到类在外部实例化并通过参数注入,而不是内联创建它。

于 2016-08-23T18:57:52.490 回答