Async providers with nestjs

I am running nestjs and I want to make an async provider. Here is my folder structure

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>.
├── dist
│ └── main.js
├── libs
│ └── dma
│ ├── src
│ │ ├── client
│ │ │ ├── client.module.ts
│ │ │ ├── client.service.spec.ts
│ │ │ └── client.service.ts
│ │ ├── cmts
│ │ │ ├── cmts.module.ts
│ │ │ ├── cmts.service.spec.ts
│ │ │ └── cmts.service.ts
│ │ ├── dma.module.ts
│ │ └── index.ts
│ └── tsconfig.lib.json
├── nest-cli.json
├── package.json
├── package-lock.json
├── README.md
├── src
│ ├── app.controller.spec.ts
│ ├── app.controller.ts
│ ├── app.module.ts
│ ├── app.service.ts
│ └── main.ts
├── test
│ ├── app.e2e-spec.ts
│ └── jest-e2e.json
├── tsconfig.build.json
└── tsconfig.json
</code>
<code>. ├── dist │ └── main.js ├── libs │ └── dma │ ├── src │ │ ├── client │ │ │ ├── client.module.ts │ │ │ ├── client.service.spec.ts │ │ │ └── client.service.ts │ │ ├── cmts │ │ │ ├── cmts.module.ts │ │ │ ├── cmts.service.spec.ts │ │ │ └── cmts.service.ts │ │ ├── dma.module.ts │ │ └── index.ts │ └── tsconfig.lib.json ├── nest-cli.json ├── package.json ├── package-lock.json ├── README.md ├── src │ ├── app.controller.spec.ts │ ├── app.controller.ts │ ├── app.module.ts │ ├── app.service.ts │ └── main.ts ├── test │ ├── app.e2e-spec.ts │ └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json </code>
.
├── dist
│   └── main.js
├── libs
│   └── dma
│       ├── src
│       │   ├── client
│       │   │   ├── client.module.ts
│       │   │   ├── client.service.spec.ts
│       │   │   └── client.service.ts
│       │   ├── cmts
│       │   │   ├── cmts.module.ts
│       │   │   ├── cmts.service.spec.ts
│       │   │   └── cmts.service.ts
│       │   ├── dma.module.ts
│       │   └── index.ts
│       └── tsconfig.lib.json
├── nest-cli.json
├── package.json
├── package-lock.json
├── README.md
├── src
│   ├── app.controller.spec.ts
│   ├── app.controller.ts
│   ├── app.module.ts
│   ├── app.service.ts
│   └── main.ts
├── test
│   ├── app.e2e-spec.ts
│   └── jest-e2e.json
├── tsconfig.build.json
└── tsconfig.json

I want to make the ClientService an async provider.

  • I want the Async operation of db connect to run first.
  • after that any dependent provider can start calling the sendSql() method.

And here are my files:

~/src/app.module.ts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { DmaModule } from '@app/dma'
@Module({
imports: [DmaModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
</code>
<code>import { Module } from '@nestjs/common' import { AppController } from './app.controller' import { AppService } from './app.service' import { DmaModule } from '@app/dma' @Module({ imports: [DmaModule], controllers: [AppController], providers: [AppService], }) export class AppModule {} </code>
import { Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { DmaModule } from '@app/dma'

@Module({
  imports: [DmaModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

~/src/app.service.ts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { CmtsService } from '@app/dma/cmts/cmts.service'
import { Injectable } from '@nestjs/common'
@Injectable()
export class AppService {
constructor(private readonly cmtsService: CmtsService) {}
getHello(): string {
return 'Hello World!'
}
}
</code>
<code>import { CmtsService } from '@app/dma/cmts/cmts.service' import { Injectable } from '@nestjs/common' @Injectable() export class AppService { constructor(private readonly cmtsService: CmtsService) {} getHello(): string { return 'Hello World!' } } </code>
import { CmtsService } from '@app/dma/cmts/cmts.service'
import { Injectable } from '@nestjs/common'

@Injectable()
export class AppService {
  constructor(private readonly cmtsService: CmtsService) {}
  getHello(): string {
    return 'Hello World!'
  }
}

~/libs/dma/client/client.module.ts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { Module } from '@nestjs/common'
import { ClientService } from './client.service'
@Module({
providers: [ClientService],
exports: [ClientService],
})
export class ClientModule {}
</code>
<code>import { Module } from '@nestjs/common' import { ClientService } from './client.service' @Module({ providers: [ClientService], exports: [ClientService], }) export class ClientModule {} </code>
import { Module } from '@nestjs/common'
import { ClientService } from './client.service'

@Module({
  providers: [ClientService],
  exports: [ClientService],
})
export class ClientModule {}

~/libs/dma/client/client.service.ts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { Injectable } from '@nestjs/common'
@Injectable()
export class ClientService {
dbConnection: any;
async connectToDb(){
// connection logic...
this.dbConnection = theConnectionObject;
}
async sendSql(sql: string){
const result = await dbConnection.send(sql) // for example
return result
}
}
</code>
<code>import { Injectable } from '@nestjs/common' @Injectable() export class ClientService { dbConnection: any; async connectToDb(){ // connection logic... this.dbConnection = theConnectionObject; } async sendSql(sql: string){ const result = await dbConnection.send(sql) // for example return result } } </code>
import { Injectable } from '@nestjs/common'

@Injectable()
export class ClientService {
  dbConnection: any;
  async connectToDb(){
    // connection logic...
    this.dbConnection = theConnectionObject;
  }
  async sendSql(sql: string){
   const result = await dbConnection.send(sql) // for example
   return result
  }
}

~/libs/dma/cmts/cmts.module.ts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { Module } from '@nestjs/common'
import { CmtsService } from './cmts.service'
import { ClientModule } from '../client/client.module'
@Module({
imports: [ClientModule],
providers: [CmtsService],
exports: [CmtsService],
})
export class CmtsModule {}
</code>
<code>import { Module } from '@nestjs/common' import { CmtsService } from './cmts.service' import { ClientModule } from '../client/client.module' @Module({ imports: [ClientModule], providers: [CmtsService], exports: [CmtsService], }) export class CmtsModule {} </code>
import { Module } from '@nestjs/common'
import { CmtsService } from './cmts.service'
import { ClientModule } from '../client/client.module'

@Module({
  imports: [ClientModule],
  providers: [CmtsService],
  exports: [CmtsService],
})
export class CmtsModule {}

~/libs/dma/cmts.service.ts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { Injectable } from '@nestjs/common'
import { ClientService } from '../client/client.service'
@Injectable()
export class CmtsService {
constructor(private readonly clientService: ClientService) {}
}
</code>
<code>import { Injectable } from '@nestjs/common' import { ClientService } from '../client/client.service' @Injectable() export class CmtsService { constructor(private readonly clientService: ClientService) {} } </code>
import { Injectable } from '@nestjs/common'
import { ClientService } from '../client/client.service'

@Injectable()
export class CmtsService {
  constructor(private readonly clientService: ClientService) {}
}

On the nestjs documentation, here’s what’s written: here

It’s written that you can do this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
provide: 'ASYNC_CONNECTION',
useFactory: async () => {
const connection = await createConnection(options);
return connection;
},
}
</code>
<code>{ provide: 'ASYNC_CONNECTION', useFactory: async () => { const connection = await createConnection(options); return connection; }, } </code>
{
  provide: 'ASYNC_CONNECTION',
  useFactory: async () => {
    const connection = await createConnection(options);
    return connection;
  },
}

But my question is.. isn’t it a bad practice to create an instance from the provider ourselves?

Because now I will have to do this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
provide: 'ASYNC_CONNECTION',
useFactory: async () => {
const clientService = new ClientService() // 👎 bad practice (?)
const connection = await clientService.connectDb();
return connection;
},
}
</code>
<code>{ provide: 'ASYNC_CONNECTION', useFactory: async () => { const clientService = new ClientService() // 👎 bad practice (?) const connection = await clientService.connectDb(); return connection; }, } </code>
{
  provide: 'ASYNC_CONNECTION',
  useFactory: async () => {
    const clientService = new ClientService() // 👎 bad practice (?)
    const connection = await clientService.connectDb();
    return connection;
  },
}

4

This is database.providers.ts where the connection is initiatied

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> export const databaseProviders = [
{
provide: 'DbConnectionToken',
useFactory: async (
environmentSettingsService: EnvironmentSettingsService
): Promise<typeof mongoose> => {
mongoose.set({ strict: false });
return await mongoose.connect(
process.env.isApiTestRunning
? testDatabaseUrl
: environmentSettingsService.config.get('usersdb')
);
},
inject: [EnvironmentSettingsService],
},
];
</code>
<code> export const databaseProviders = [ { provide: 'DbConnectionToken', useFactory: async ( environmentSettingsService: EnvironmentSettingsService ): Promise<typeof mongoose> => { mongoose.set({ strict: false }); return await mongoose.connect( process.env.isApiTestRunning ? testDatabaseUrl : environmentSettingsService.config.get('usersdb') ); }, inject: [EnvironmentSettingsService], }, ]; </code>
 export const databaseProviders = [
  {
    provide: 'DbConnectionToken',
    useFactory: async (
      environmentSettingsService: EnvironmentSettingsService
    ): Promise<typeof mongoose> => {
      mongoose.set({ strict: false });
      return await mongoose.connect(
        process.env.isApiTestRunning
          ? testDatabaseUrl
          : environmentSettingsService.config.get('usersdb')
      );
    },
    inject: [EnvironmentSettingsService],
  },
];

My schema token provider class – where i inject the schema with initiated connection. MyAppPRoviders.ts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> export const MyAppProviders = [
{
provide: modelTokens.UsersToken,
useFactory: (connection: Connection) => connection.model(dbCollections.users, UsersSchema),
inject: ["DbConnectionToken"],
},
</code>
<code> export const MyAppProviders = [ { provide: modelTokens.UsersToken, useFactory: (connection: Connection) => connection.model(dbCollections.users, UsersSchema), inject: ["DbConnectionToken"], }, </code>
 export const MyAppProviders = [
  {
    provide: modelTokens.UsersToken,
    useFactory: (connection: Connection) => connection.model(dbCollections.users, UsersSchema),
    inject: ["DbConnectionToken"],
  },

You will have to initiate these in your modules – i am assuming you already know this

How to use these schema provider token in services? I will inject below in one of my service class where i want to use the user model to perform DB operation on users collection

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Injectable()
export class UserCrud {
private similaritySearch: any;
constructor(
@Inject(modelTokens.UsersToken)
private usersModel: Model<any>)
{}
// Your code
//using userModel
await this.usersModel.findOne({}).....
....
}
</code>
<code>Injectable() export class UserCrud { private similaritySearch: any; constructor( @Inject(modelTokens.UsersToken) private usersModel: Model<any>) {} // Your code //using userModel await this.usersModel.findOne({})..... .... } </code>
Injectable()
export class UserCrud {
    private similaritySearch: any;

    constructor(
        @Inject(modelTokens.UsersToken)
        private usersModel: Model<any>)
    {}
// Your code
//using userModel
await this.usersModel.findOne({}).....
....
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật