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?
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:
serviceRequiredclass extending SqlBaseCrudService
tableRequiredDrizzle table
configOptionalCrudFeatureConfig
Several services can share one call. Each becomes its own provider, built independently:
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:
- Project defaults. The
forRootorforRootAsyncconfig, with defaults filled in for soft delete, timestamps, pagination and thesqlflags. - Per entity. The
@CrudServicedecorator metadata, then theconfigobject fromforFeature, then the injecteddband thetable. - 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:
primaryKeyOptionalstring
Defaults to "id"
softDelete.enabledOptionalboolean
Defaults to project (true)
softDelete.columnOptionalstring
Defaults to "deleted_at"
timestamps.createdAtOptionalstring
Defaults to "created_at"
timestamps.updatedAtOptionalstring
Defaults to "updated_at"
pagination.defaultLimitOptionalnumber
Defaults to project (20)
pagination.maxLimitOptionalnumber
Defaults to project (100)
defaultSortOptionalSortColumn[]
sql.caseSensitiveOptionalboolean
Defaults to project (false)
sql.useReturningOptionalboolean
Defaults to project
relationsOptionalRelationsConfig
scopeOptionalobject | (ctx) => object
versionColumnOptionalstring
filterableColumnsOptionalstring[]
sortableColumnsOptionalstring[]
selectableColumnsOptionalstring[]
searchableColumnsOptionalstring[]
loadableRelationsOptionalstring[]
writableColumnsOptionalstring[]
writableRelationsOptionalstring[]
primaryKeyTypeOptionalstring
Each of these has its own page: relations, multi-tenancy for scope, optimistic locking for versionColumn, and allowlists for the column lists.
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:
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:
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:
const posts = moduleRef.get(PostsService);
expect((posts as any).config.pagination).toEqual({ defaultLimit: 5, maxLimit: 100 });Common questions
No. forFeature provides and exports it. Listing it again makes Nest build a second instance without a config, which fails at startup.
The forFeature config. The merge order is project defaults, then decorator metadata, then forFeature config, then the injected db and table.
No. softDelete, timestamps, pagination and sql merge one level deep, so pagination: { defaultLimit: 5 } keeps the project maxLimit.
Set timestamps: undefined in that entity's forFeature config. An explicit undefined replaces the project value.
No. It is the normalized project config only. Each service holds its own merged config.
Next steps
Defining services
An empty subclass, and when to add methods of your own.
NestJS CRUD controller generator
Generate the REST routes for a registered service.
Config types
The full SqlCrudConfig and CrudFeatureConfig types.
SQLite, libSQL and Cloudflare D1
Use NestJS with Drizzle on SQLite, libSQL (Turso) or Cloudflare D1. What works, what is a 400, and why D1 cannot run bulk writes or nested creates.
Test a NestJS Drizzle CRUD service
Test a NestJS Drizzle CRUD service against real SQL in memory with PGlite, or unit test it with TestCrudFactory and a Jest mock database.