Drizzle forRootAsync with ConfigService

NestJS Drizzle forRootAsync with ConfigService builds the database config at startup, from useFactory, useClass or useExisting and any provider you inject.

DrizzleCrudModule.forRootAsync({ imports, inject, useFactory }) is the async form of forRoot for NestJS Drizzle apps that read their config from ConfigService. Nest calls your useFactory at startup with the providers listed in inject, and the object it returns (or resolves to) is the same DrizzleCrudConfig that forRoot takes, with the same defaults filled in. Since 3.7.0 it also takes useClass or useExisting, the usual Nest way to build options from a class.

Give exactly one of useFactory, useClass or useExisting

With none of them, or with more than one, forRootAsync throws when the module is declared, and the message names what it got. Before 3.7.2 useFactory silently won over the other two.

What does forRootAsync take?

DrizzleCrudModule.forRootAsync(options: DrizzleCrudAsyncOptions): DynamicModule

interface DrizzleCrudAsyncOptions {
  imports?: any[];
  inject?: any[];
  useFactory?: (...deps: any[]) => DrizzleCrudConfig | Promise<DrizzleCrudConfig>;
  useClass?: Type<DrizzleCrudOptionsFactory>;
  useExisting?: Type<DrizzleCrudOptionsFactory>;
}

interface DrizzleCrudOptionsFactory {
  createDrizzleCrudOptions(): DrizzleCrudConfig | Promise<DrizzleCrudConfig>;
}
useFactoryOptional

(...deps) => config

Returns a DrizzleCrudConfig, or a promise of one. Receives the providers in inject, in the same order.
useClassOptional

Type<DrizzleCrudOptionsFactory>

A class the module registers and instantiates, then asks for the config with createDrizzleCrudOptions(). Its constructor can inject any provider in scope.
useExistingOptional

Type<DrizzleCrudOptionsFactory>

A provider that already exists, usually exported by a module in imports. The module calls its createDrizzleCrudOptions() and does not create a second instance.
injectOptional

any[]

Providers to pass to useFactory, such as ConfigService. Not used with useClass or useExisting.

Defaults to []

importsOptional

any[]

Modules that export the injected providers. Not needed for a global module such as ConfigModule with isGlobal: true.

Defaults to []

The module is global, exactly like forRoot, and exports the same tokens (DRIZZLE_DB, DRIZZLE_CRUD_CONFIG, DRIZZLE_CONNECTION, CrudEventBus).

How do I read the config from ConfigService?

Install @nestjs/config

pnpm add @nestjs/config

Inject ConfigService into the factory

app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { DrizzleCrudModule } from '@avytrix/nestjs-drizzle-crud';
import * as schema from './db/schema';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    DrizzleCrudModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        dialect: 'postgresql',
        connectionString: config.getOrThrow<string>('DATABASE_URL'),
        schema,
        defaults: {
          pagination: { defaultLimit: 20, maxLimit: 100 },
        },
      }),
    }),
  ],
})
export class AppModule {}

getOrThrow stops startup with a clear error when the variable is missing, instead of failing later on the first query.

How do I build my own Drizzle instance in the factory?

Return db instead of connectionString. Use this on SQLite, libSQL and D1, or for a driver option that connection (pool size, SSL, idle timeout) does not cover:

app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { DrizzleCrudModule } from '@avytrix/nestjs-drizzle-crud';
import * as schema from './db/schema';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    DrizzleCrudModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        const client = postgres(config.getOrThrow<string>('DATABASE_URL'), {
          max: config.get<number>('DB_POOL_SIZE', 10),
        });
        return { dialect: 'postgresql', db: drizzle(client, { schema }) };
      },
    }),
  ],
})
export class AppModule {}

A db you pass in is yours: the module does not close it on shutdown. Only a connection the module built from connectionString is closed for you.

Can the factory be async?

Yes. Return a promise when you fetch a value at startup, for example a password from a secrets manager:

app.module.ts
DrizzleCrudModule.forRootAsync({
  imports: [SecretsModule],
  inject: [ConfigService, SecretsService],
  useFactory: async (config: ConfigService, secrets: SecretsService) => ({
    dialect: 'postgresql',
    connectionString: await secrets.get('DATABASE_URL'),
    schema,
    sql: { caseSensitive: config.get<boolean>('CASE_SENSITIVE_FILTERS', false) },
  }),
})

SecretsModule and SecretsService stand for your own module. Nest waits for the promise before it builds any service, so a rejected promise stops startup.

How do I use a config class with useClass?

Implement DrizzleCrudOptionsFactory and pass the class as useClass. The module registers it, injects its constructor and calls createDrizzleCrudOptions():

crud-config.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type {
  DrizzleCrudConfig,
  DrizzleCrudOptionsFactory,
} from '@avytrix/nestjs-drizzle-crud';
import * as schema from './db/schema';

@Injectable()
export class CrudConfigService implements DrizzleCrudOptionsFactory {
  constructor(private readonly config: ConfigService) {}

  createDrizzleCrudOptions(): DrizzleCrudConfig {
    return {
      dialect: 'postgresql',
      connectionString: this.config.getOrThrow<string>('DATABASE_URL'),
      connection: { poolSize: this.config.get<number>('DB_POOL_SIZE', 10) },
      schema,
    };
  }
}
app.module.ts
DrizzleCrudModule.forRootAsync({ useClass: CrudConfigService })

ConfigService resolves here because ConfigModule is global. For a provider from a module that is not global, add that module to imports.

How do I reuse a provider with useExisting?

When the config class is already a provider in another module, export it from there and pass useExisting. The module asks that instance for the config instead of creating its own:

app.module.ts
@Module({ providers: [CrudConfigService], exports: [CrudConfigService] })
export class CrudConfigModule {}

DrizzleCrudModule.forRootAsync({
  imports: [CrudConfigModule],
  useExisting: CrudConfigService,
})

When should I use forRoot instead?

Use forRoot when the config is a plain object you can build when the module file loads. Use forRootAsync when any of these hold:

  • The connection string goes through ConfigService and its validation.
  • The Drizzle instance is built from config values, such as the pool size.
  • The config depends on another provider: feature flags, a secrets manager, a tenant registry.

Common questions

Next steps

Last updated View change history

On this page