Drizzle forFeature in NestJS

Drizzle forFeature in NestJS binds each CRUD service to its table and merges per-entity config over the project defaults from forRoot, one level deep.

DrizzleCrudModule.forFeature(entities) is the Drizzle forFeature call for NestJS feature modules. It binds each CRUD service to its Drizzle table, builds the service with the project defaults from forRoot merged with any per-entity config, and exports it so your controllers can inject it. Call it once per feature module, with one entry per service.

Do not list the service in providers

forFeature already provides and exports the service. Adding it to the module's providers makes Nest construct it a second time without the merged config, and startup fails. Services are not @Injectable() for the same reason.

How do I register a service?

users/users.module.ts
import { Module } from '@nestjs/common';
import { DrizzleCrudModule } from '@avytrix/nestjs-drizzle-crud';
import { users } from '../db/schema';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
  imports: [DrizzleCrudModule.forFeature([{ service: UsersService, table: users }])],
  controllers: [UsersController],
})
export class UsersModule {}

Each entry is a CrudFeature:

serviceRequired

class extending SqlBaseCrudService

The service class. It is also the injection token.
tableRequired

Drizzle table

The table the service reads and writes.
configOptional

CrudFeatureConfig

Per-entity overrides. Every key is optional.

Several services can share one call. Each becomes its own provider, built independently:

blog/blog.module.ts
DrizzleCrudModule.forFeature([
  { service: UsersService, table: users },
  { service: PostsService, table: posts, config: postsCrud },
  { service: CommentsService, table: comments, config: { softDelete: { enabled: false } } },
])

In what order do the config layers merge?

Config reaches a service through three layers, and each one overrides the one before:

  1. Project defaults. The forRoot or forRootAsync config, with defaults filled in for soft delete, timestamps, pagination and the sql flags.
  2. Per entity. The @CrudService decorator metadata, then the config object from forFeature, then the injected db and the table.
  3. Service construction. The service constructor spreads the result over its own built-in defaults and validates it.

softDelete, timestamps, pagination and sql merge one level deep at every layer, so an override names only what it changes. pagination: { defaultLimit: 5 } keeps the project's maxLimit, and sql: { caseSensitive: true } keeps useReturning. Every other key replaces the value below it. timestamps: undefined turns timestamps off for that entity.

When behaviour looks wrong, check which layer set the value before you look anywhere else.

What can I override per entity?

The type is CrudFeatureConfig. Defaults marked "project" come from forRoot:

primaryKeyOptional

string

The key of the primary key column in the table object.

Defaults to "id"

softDelete.enabledOptional

boolean

Soft delete for this entity.

Defaults to project (true)

softDelete.columnOptional

string

The key of the soft-delete column in the table object, not the SQL name.

Defaults to "deleted_at"

timestamps.createdAtOptional

string

Key of the created-at column. Set timestamps: undefined to turn timestamps off.

Defaults to "created_at"

timestamps.updatedAtOptional

string

Key of the updated-at column.

Defaults to "updated_at"

pagination.defaultLimitOptional

number

Rows per page for this entity.

Defaults to project (20)

pagination.maxLimitOptional

number

Highest limit a caller may ask for on this entity.

Defaults to project (100)

defaultSortOptional

SortColumn[]

ORDER BY for findAll when the caller sends no sortBy, applied in order. The primary key is always added last.
sql.caseSensitiveOptional

boolean

Case sensitivity of bare string filters for this entity.

Defaults to project (false)

sql.useReturningOptional

boolean

RETURNING after writes for this entity.

Defaults to project

relationsOptional

RelationsConfig

belongsTo, hasMany and manyToMany relations keyed by name.
scopeOptional

object | (ctx) => object

Column values ANDed into every read and write, such as a tenant id.
versionColumnOptional

string

An integer column for optimistic locking. A stale version is a 409.
filterableColumnsOptional

string[]

Columns a caller may filter by. Unset allows all.
sortableColumnsOptional

string[]

Columns a caller may sort by. Unset allows all.
selectableColumnsOptional

string[]

Columns a caller may select. Unset allows all.
searchableColumnsOptional

string[]

Columns search may look in. Unset allows all.
loadableRelationsOptional

string[]

Relations a caller may load or count. Unset allows all.
writableColumnsOptional

string[]

Columns create, update and upsert may write; any other column is a 400.
writableRelationsOptional

string[]

Relations a create body may write, and that attach, detach and sync may change.
primaryKeyTypeOptional

string

Deprecated, no effect. The key type comes from the Drizzle column.

Each of these has its own page: relations, multi-tenancy for scope, optimistic locking for versionColumn, and allowlists for the column lists.

posts/posts.module.ts
DrizzleCrudModule.forFeature([
  {
    service: PostsService,
    table: posts,
    config: {
      softDelete: { enabled: true },
      defaultSort: [
        { column: 'position', order: 'asc' },
        { column: 'created_at', order: 'desc' },
      ],
      relations: {
        author: { table: users, localKey: 'author_id', references: 'id' },
      },
      filterableColumns: ['title', 'author_id', 'author.name'],
    },
  },
])

Does a camelCase schema need extra config?

Yes, when your keys differ from the defaults. Settings name the key in the Drizzle table object, not the database column. For deletedAt: timestamp('deleted_at') and friends:

users/users.module.ts
DrizzleCrudModule.forFeature([
  {
    service: UsersService,
    table: users,
    config: {
      softDelete: { column: 'deletedAt' },
      timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' },
    },
  },
])

The service checks these keys when it is built. A key that is not on the table stops the app with a message that names the right one, for example: softDelete.column is "deleted_at", but the table has no column under that key. The column "deleted_at" is declared under the key "deletedAt"; set softDelete.column to "deletedAt".

Can I put the config on the service class?

Yes, with @CrudService. Its metadata is the first per-entity layer, so forFeature config wins where both set a key, and the forFeature table wins over the decorator's. The decorator's type asks for dialect, table and primaryKey:

tags/tags.service.ts
import { type CrudFilter, CrudService, SqlBaseCrudService } from '@avytrix/nestjs-drizzle-crud';
import { tags } from '../db/schema';
import type { CreateTagDto } from './dto/create-tag.dto';
import type { UpdateTagDto } from './dto/update-tag.dto';

type Tag = typeof tags.$inferSelect;

@CrudService({
  dialect: 'postgresql',
  table: tags,
  primaryKey: 'id',
  softDelete: { enabled: true, column: 'deleted_at' },
  filterableColumns: ['name'],
})
export class TagsService extends SqlBaseCrudService<Tag, CreateTagDto, UpdateTagDto, CrudFilter> {}

The decorator keeps the config next to the service, and it lets ApiCrudList and the controller factory's openapi: true read the table and allowlists from the class. For config that varies per module, keep it in forFeature, or in a shared constant you spread into both.

How do I check the merged config?

DRIZZLE_CRUD_CONFIG holds only the project layer: dialect, defaults, sql and hooks.enableGlobalHooks, with defaults filled in. It does not include per-entity overrides. The fully merged config of one entity lives on the service as the protected config property, which a test can read:

posts.module.spec.ts
const posts = moduleRef.get(PostsService);
expect((posts as any).config.pagination).toEqual({ defaultLimit: 5, maxLimit: 100 });

Common questions

Next steps

Last updated View change history

On this page