我需要在 NodeJS 中进行依赖注入,或者如何处理...? [英] Do I need dependency injection in NodeJS, or how to deal with ...?

查看:26
本文介绍了我需要在 NodeJS 中进行依赖注入,或者如何处理...?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 nodejs 创建一些实验项目.我已经使用 Spring 编写了很多 Java EE Web 应用程序,并且很欣赏那里的依赖注入的便利性.

I currently creating some experimental projects with nodejs. I have programmed a lot Java EE web applications with Spring and appreciated the ease of dependency injection there.

现在我很好奇:如何使用节点进行依赖注入?或者:我什至需要它吗?有没有替代的概念,因为编程风格不同?

Now I am curious: How do I do dependency injection with node? Or: Do I even need it? Is there a replacing concept, because the programming style is different?

我说的是简单的事情,比如共享一个数据库连接对象,到目前为止,但我还没有找到一个让我满意的解决方案.

I am talking about simple things, like sharing a database connection object, so far, but I have not found a solution that satisfies me.

推荐答案

简而言之,您不需要像在 C#/Java 中那样的依赖注入容器或服务定位器.由于 Node.js 利用了模块模式,因此不需要执行构造函数或属性注入.虽然你仍然可以.

In short, you don't need a dependency injection container or service locater like you would in C#/Java. Since Node.js, leverages the module pattern, it's not necessary to perform constructor or property injection. Although you still can.

JS 的伟大之处在于你可以修改任何东西来实现你想要的.这在测试时会派上用场.

The great thing about JS is that you can modify just about anything to achieve what you want. This comes in handy when it comes to testing.

看我非常蹩脚的人为例子.

Behold my very lame contrived example.

MyClass.js:

var fs = require('fs');

MyClass.prototype.errorFileExists = function(dir) {
    var dirsOrFiles = fs.readdirSync(dir);
    for (var d of dirsOrFiles) {
        if (d === 'error.txt') return true;
    }
    return false;
};

MyClass.test.js:

describe('MyClass', function(){
    it('should return an error if error.txt is found in the directory', function(done){
        var mc = new MyClass();
        assert(mc.errorFileExists('/tmp/mydir')); //true
    });
});

注意 MyClass 如何依赖 fs 模块?正如@ShatyemShekhar 所提到的,您确实可以像在其他语言中一样进行构造函数或属性注入.但在 Javascript 中没有必要.

Notice how MyClass depends upon the fs module? As @ShatyemShekhar mentioned, you can indeed do constructor or property injection as in other languages. But it's not necessary in Javascript.

在这种情况下,您可以做两件事.

In this case, you can do two things.

您可以存根 fs.readdirSync 方法,也可以在调用 require 时返回一个完全不同的模块.

You can stub the fs.readdirSync method or you can return an entirely different module when you call require.

方法一:

var oldmethod = fs.readdirSync;
fs.readdirSync = function(dir) { 
    return ['somefile.txt', 'error.txt', 'anotherfile.txt']; 
};

*** PERFORM TEST ***
*** RESTORE METHOD AFTER TEST ****
fs.readddirSync = oldmethod;

方法二:

var oldrequire = require
require = function(module) {
    if (module === 'fs') {
        return {
            readdirSync: function(dir) { 
                return ['somefile.txt', 'error.txt', 'anotherfile.txt']; 
            };
        };
    } else
        return oldrequire(module);
            
}

关键是要利用 Node.js 和 Javascript 的强大功能.请注意,我是一个 CoffeeScript 人,所以我的 JS 语法可能在某处不正确.另外,我并不是说这是最好的方法,但它是一种方法.Javascript 专家可能会配合其他解决方案.

The key is to leverage the power of Node.js and Javascript. Note, I'm a CoffeeScript guy, so my JS syntax might be incorrect somewhere. Also, I'm not saying that this is the best way, but it is a way. Javascript gurus might be able to chime in with other solutions.

更新:

这应该可以解决您关于数据库连接的具体问题.我会创建一个单独的模块来封装您的数据库连接逻辑.像这样:

This should address your specific question regarding database connections. I'd create a separate module to encapsulate your database connection logic. Something like this:

MyDbConnection.js:(一定要选择更好的名字)

MyDbConnection.js: (be sure to choose a better name)

var db = require('whichever_db_vendor_i_use');

module.exports.fetchConnection() = function() {
    //logic to test connection
    
    //do I want to connection pool?
    
    //do I need only one connection throughout the lifecyle of my application?
    
    return db.createConnection(port, host, databasename); //<--- values typically from a config file    
}

然后,任何需要数据库连接的模块都将只包含您的 MyDbConnection 模块.

Then, any module that needs a database connection would then just include your MyDbConnection module.

SuperCoolWebApp.js:

var dbCon = require('./lib/mydbconnection'); //wherever the file is stored

//now do something with the connection
var connection = dbCon.fetchConnection(); //mydbconnection.js is responsible for pooling, reusing, whatever your app use case is

//come TEST time of SuperCoolWebApp, you can set the require or return whatever you want, or, like I said, use an actual connection to a TEST database. 

不要逐字逐句地遵循这个例子.这是一个试图传达您利用 module 模式来管理依赖项的蹩脚示例.希望这会有所帮助.

Do not follow this example verbatim. It's a lame example at trying to communicate that you leverage the module pattern to manage your dependencies. Hopefully this helps a bit more.

这篇关于我需要在 NodeJS 中进行依赖注入,或者如何处理...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆