简体   繁体   中英

How to use service/module inside of another module?

In the main.ts file of my nestJS application I would like to add some fixture data to my database if the app is starting in dev mode:

const app = await NestFactory.create(AppModule)
await app.listen(port, async () => {

  if (!production) {
    const User = this.db.collection('user')
    await User.deleteMany({})
    await User.insertMany(user)
  }
})

Of course this is not working, as I do not have db at this time.

I'm defining the database connection in a module and this is how my database.module.ts looks like. Is it possible to put the fixtures parts (drop database and add fixture data) in the database.module? The reason why I think I have to add it to the main.ts is that I need to run it on application start, not at every db connection.

import { Module, Inject } from '@nestjs/common'
import { MongoClient, Db } from 'mongodb'

@Module({
  providers: [
    {
      provide: 'DATABASE_CLIENT',
      useFactory: () => ({ client: null })
    },
    {
      provide: 'DATABASE_CONNECTION',
      inject: ['DATABASE_CLIENT'],
      useFactory: async (dbClient): Promise<Db> => {
        try {
          const client = await MongoClient.connect('mongodb://localhost:27017')
          dbClient.client = client
          const db = client.db('database')
          return db
        } catch (error) {
          console.error(error)
          throw error
        }
      }
    }
  ],
  exports: ['DATABASE_CONNECTION', 'DATABASE_CLIENT']
})
export class DatabaseModule {
  constructor(@Inject('DATABASE_CLIENT') private dbClient) {}
  async onModuleDestroy() {
    await this.dbClient.client.close()
  }
}

With that I can use my db in every other module, but that doesn't help me to get db connection at start up of the application:

import { Module } from '@nestjs/common'
import { MyService } from './my.service'
import { MyResolvers } from './my.resolvers'
import { DatabaseModule } from '../database.module'

@Module({
  imports: [DatabaseModule],
  providers: [MyService, MyResolvers]
})
export class MyModule {}

If you're looking to get the database client in your main.ts you need to get into the client from the container system nest has. You can do that with the following line, used before your app.listen()

const db = app.get('DATABASE_CLIENT', { strict: false })

And then instead of this.db you'll just use db.client.collection()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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