#Custom Providers + useClass

4 messages · Page 1 of 1 (latest)

pseudo fiber
#

Hey all, I'm working on setting up a custom provider for the database. I've built it much in the same vein as e.g. nestjs/mongoose etc, and i have a setup in one of the consuming services that looks like this:


// in app.module.ts...


@Module({
  imports: [
    DatabaseModule.forRootAsync({
      imports: [ConfigModule],
      // useClass: DatabaseConfigService,
      useFactory: (config: ConfigService) => {
        const {
          MONGODB_SCHEMA,
          MONGODB_URI,
          MONGODB_USER,
          MONGODB_PASS,
          MONGODB_CERT,
        } = config.get<any>('SERVICE_NAME');

        const dbOpts: DatabaseModuleOptions = {};

        dbOpts.uri = MONGODB_URI;
        dbOpts.auth = { username: MONGODB_USER, password: MONGODB_PASS };
        dbOpts.certData = MONGODB_CERT;
        dbOpts.schema = MONGODB_SCHEMA;

        return dbOpts;
      },
      inject: [ConfigService, DatabaseModuleOptions],
    }),
  ]
})

While this is all well and good, i'd love to figure otu how to switch this to use some kind of static/class to generate the dbOpts -- even if i was pulling them in via args to the factory (and not building the moduleOptions) it'd still be quite a bit of repetitive code across several microservices, so if there was a way i could 'bundle' this setup step into the db library, i'd be grateful.

#

oh. you know what? useClass is not what i think it is. it's for figuring out which class the provider should use, not a class that sorts out the args. so all i think i need to do is continue to use the factory, but pass a static singleton function call

#

like, how can i pass things (e.g. the config object) into that ConfigService class?