简体   繁体   English

如何在 NestJS 中正确集成 sql 连接库

[英]How to integrate a sql connection lib properly in NestJS

I'm wondering if there's a good pratice in order to use the library "mssql" in NestJS, whether if I should make a new module (and how, I'm pretty new to NestJS) or something else to implement singleton pattern for example.我想知道在 NestJS 中使用库“mssql”是否有很好的实践,是否应该创建一个新模块(以及如何,我对 NestJS 很新)或其他东西来实现单例模式.

I also noticed that the library comes with an audit vulnerability from axios package.我还注意到该库带有来自 axios 包的审计漏洞。 Should I worry about this ?我应该担心这个吗?

Thanks for you help,谢谢你的帮助,

I would make it a custom provider and add it and export it as a part of a module.我会将其设为自定义提供程序并添加它并将其作为模块的一部分导出。 Something like this:像这样的东西:

// mssql.constants.ts
export const MSSQL_TOKEN = Symbol('mssql');

// mssql.module.ts
@Module({
  providers: [
    {
      provide: MSSQL_TOKEN,
      useFactory: async () => await mssql.connect(connectionString),
    }
  ],
  exports: [MSSQL_TOKEN],
})
export class MssqlModule {}

And now you can add the MssqlModule to the imports of whatever module that has a service that needs to use the mssql connection and in that service use @Inject(MSSQL_TOKEN) in the constructor, and then you're good to go.现在您可以将MssqlModule添加到具有需要使用mssql连接的服务的任何模块的imports ,并在该服务中使用@Inject(MSSQL_TOKEN)在构造函数中,然后您就可以开始了。 You can get fancier with a dynamic module , but this should be a good start.您可以使用动态模块变得更有趣,但这应该是一个好的开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM