@elsikora/nestjs-crud-config

中文文档
5.1.0发布于 2026/11/04MITTypeScriptES Module近 30 天下载 7382

NestJS application configuration via database storage

原始使用文档
文档目录46 节
  1. 📚 Table of Contents
  2. 📖 Description
  3. 🚀 Features
  4. 🛠 Installation
  5. Prerequisites
  6. Automator 5 compatibility
  7. Migrating to 5.0
  8. Database Support
  9. 💡 Usage
  10. Basic Setup
  11. Using the Configuration Service
  12. Async Module Registration
  13. 🚀 Migration System
  14. Key Features
  15. Migration Status Enum
  16. Basic Migration Configuration
  17. Creating Migration Files
  18. Environment-Specific Migrations
  19. Advanced Migration Configuration
  20. Migration Best Practices
  21. Migration Monitoring
  22. Testing Migrations
  23. 📚 API Documentation
  24. Configuration Sections (default: /config/section )
  25. Configuration Data (default: /config/data )
  26. Customizing API Endpoints
  27. 🗄️ Database Schema
  28. Configuration Sections Table ( config_section )
  29. Configuration Data Table ( config_data )
  30. 🔧 Advanced Configuration
  31. Encryption Support
  32. Transaction and Duplicate Protection
  33. Headless Mode (Without Controllers)
  34. Working with Multiple Environments
  35. 🛣 Roadmap
  36. ❓ FAQ
  37. What databases are supported?
  38. How does this compare to environment variables?
  39. Can I migrate from environment variables?
  40. How do I handle sensitive configuration data?
  41. Can I use this with microservices?
  42. How do I customize table names and field sizes?
  43. What happens if the database is unavailable?
  44. Can I use this without REST API endpoints?
  45. Is this production-ready?
  46. 🔒 License

project-logo

NestJS CRUD Config 🚀

Database-backed configuration management for NestJS applications with full CRUD capabilities

ElsiKora TypeScript NestJS Node.js PostgreSQL MySQL SQLite MongoDB Swagger

📚 Table of Contents

📖 Description

NestJS CRUD Config is a powerful configuration management module that revolutionizes how NestJS applications handle configuration data. Unlike traditional environment variable approaches, this library stores configuration in a database with full CRUD operations, making it perfect for dynamic configuration management across multiple environments and services.

The module provides hierarchical organization through sections and data entries, supports optional AES-256-GCM encryption for sensitive values, and includes automatic REST API endpoints for configuration management. Built with TypeScript-first design and leveraging the NestJS CRUD Automator for automatic API generation, it features dynamic entity creation at runtime, named transaction ownership, and intelligent caching.

Whether you're managing API keys across different environments, storing feature flags, or maintaining application settings that need to change without redeployment, this module provides a robust, secure, and scalable solution for microservice architectures, multi-tenant applications, and any system requiring centralized, database-backed configuration management with real-time updates.

🚀 Features

  • 🗄️ Database-backed configuration storage - Store configuration in any TypeORM-supported database for persistence and scalability
  • 🏗️ Dynamic entity creation - Entities are created at runtime with customizable table names, field lengths, and constraints
  • 📊 Hierarchical organization - Organize configuration using sections and data entries for better structure and management
  • 🔐 AES-256-GCM encryption support - Protect sensitive configuration values with built-in encryption using industry-standard algorithms
  • 🌍 Multi-environment support - Manage configurations across development, staging, and production environments seamlessly
  • ⚡ Full CRUD operations - Complete Create, Read, Update, Delete operations with automatic REST API endpoints
  • 📚 Automatic Swagger documentation - Generated OpenAPI documentation for all configuration endpoints
  • 🎯 TypeScript-first design - Full type safety with comprehensive interfaces and type definitions
  • 🚀 NestJS CRUD Automator integration - Leverages advanced CRUD automation for controllers and services
  • 💾 Intelligent caching - Built-in caching support with configurable TTL and cache size limits
  • 🔄 Named transaction ownership - Each Automator-owned unit of work uses one exact TypeORM manager, including joined migration writes
  • 🎛️ Highly customizable - Configure table prefixes, field lengths, validation rules, and entity relationships
  • 🚦 Flexible controller configuration - Customize API paths, disable endpoints, or run in headless mode
  • 🔧 Advanced CRUD customization - Full control over routes, swagger documentation, and controller behavior
  • 📦 Modular architecture - Enable/disable features as needed for your use case
  • 🚀 Production-ready migration system - Initialize and manage configuration state during application startup

🛠 Installation

These docs describe the CrudConfig 5 contract: Automator 5, NestJS 12, TypeORM 1, ES modules only. Use the 5.x range, which also accepts the 5.0.0 prereleases:

# npm
npm install @elsikora/nestjs-crud-config@^5.0.0-0

# yarn
yarn add @elsikora/nestjs-crud-config@^5.0.0-0

# pnpm
pnpm add @elsikora/nestjs-crud-config@^5.0.0-0

Prerequisites

Node.js ^22.13.0 || >=24.11.0. Install the required peer dependencies:

npm install @elsikora/nestjs-crud-automator@^5.0.0-0 @nestjs/common@^12 @nestjs/core@^12 @nestjs/typeorm@^12 typeorm@^1
npm install @nestjs/passport@^12 @nestjs/platform-fastify@^12 @nestjs/swagger@^12 @nestjs/throttler class-transformer class-validator fastify lodash

The package ships as ES modules only. CommonJS applications keep require("@elsikora/nestjs-crud-config"), which Node.js loads through require(esm). Importing the package loads no .env file: set NCC_LOG_LEVEL in the environment, or load .env in the application, for example with ConfigModule.forRoot().

Automator 5 compatibility

CrudConfig 5 requires @elsikora/nestjs-crud-automator ^5.0.0. Automator 4 and older are not supported.

Generated routes run Automator's ApiAuthorizationGuard. When the section or data controllers are enabled, import Automator's global ApiAuthorizationModule once in the root module, as the examples below do; without it the application fails at startup with Nest can't resolve dependencies of the ApiAuthorizationGuard. Headless mode does not need it.

Generated route overrides continue to use Automator generation config:

DELETE: {
 generation: {
  isEnabled: false,
 },
},

ConfigData CREATE and UPDATE use Automator nested request relation loading. The built-in section relation expects request bodies such as { "section": { "id": "section-uuid" } }.

CrudConfig creates each generated service through createDynamicService() and @ApiService({ entity }), so its inherited same-entity CRUD methods satisfy the Automator generated-route capability boundary. Applications do not need a wrapper or compatibility layer.

Migrating to 5.0

CrudConfig 5 moves to the latest majors and ships as ES modules only. The CrudConfig runtime contract is otherwise unchanged:

  • peers move to Automator 5, NestJS 12, Swagger 12, @nestjs/typeorm 12 and TypeORM 1; Node.js ^22.13.0 || >=24.11.0;
  • the build is ESM only: dist/esm, dist/cjs and the require export condition are gone, CommonJS applications load the package through require(esm);
  • the @nestjs/cache-manager dependency moves to 12, so npm ci no longer fails with ERESOLVE on NestJS 12;
  • the package no longer imports dotenv/config: it never loads .env, and NCC_LOG_LEVEL comes from the application's environment;
  • module options, CrudConfigService, generated routes, the database schema and transaction ownership do not change.

See the complete 5.0 migration guide. The 4.0 and 3.0 migration guides remain available for older upgrades.

Database Support

This package works with any database supported by TypeORM:

  • PostgreSQL
  • MySQL/MariaDB
  • SQLite (through the better-sqlite3 driver; TypeORM 1 removes sqlite)
  • Microsoft SQL Server
  • Oracle
  • MongoDB
  • CockroachDB

💡 Usage

Basic Setup

// app.module.ts
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ApiAuthorizationModule } from "@elsikora/nestjs-crud-automator";
import { CrudConfigModule, TOKEN_CONSTANT } from "@elsikora/nestjs-crud-config";

@Module({
 imports: [
  // Automator's generated routes run ApiAuthorizationGuard; import this global module once in the root module
  ApiAuthorizationModule,
  // First register CrudConfigModule to create dynamic entities
  CrudConfigModule.register({
   environment: "development",
   shouldAutoCreateSections: true,

   // Cache configuration
   cacheOptions: {
    isEnabled: true,
    maxCacheItems: 1000,
    maxCacheTTL: 3600000, // 1 hour in milliseconds
   },

   // Encryption configuration
   encryptionOptions: {
    isEnabled: true,
    encryptionKey: process.env.CONFIG_ENCRYPTION_KEY, // 32+ character key
   },

   // Controller configuration (optional)
   controllersOptions: {
    section: {
     isEnabled: true,
     properties: {
      path: "api/config/sections",
     },
    },
    data: {
     isEnabled: true,
     properties: {
      path: "api/config/data",
     },
    },
   },

   // Entity customization
   entityOptions: {
    tablePrefix: "app_",
    timestampColumnType: "timestamptz", // PostgreSQL; defaults to Date, the timestamp type of the driver
    configSection: {
     tableName: "config_sections",
     maxNameLength: 128,
     maxDescriptionLength: 512,
    },
    configData: {
     tableName: "config_data",
     maxValueLength: 8192,
     maxEnvironmentLength: 64,
     maxNameLength: 128,
     maxDescriptionLength: 512,
    },
   },
  }),

  // Then register TypeORM with dynamic entities using registerAsync
  TypeOrmModule.forRootAsync({
   imports: [CrudConfigModule],
   inject: [TOKEN_CONSTANT.CONFIG_SECTION_ENTITY, TOKEN_CONSTANT.CONFIG_DATA_ENTITY],
   useFactory: async (sectionEntity, dataEntity) => ({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "postgres",
    password: "postgres",
    database: "config_db",
    entities: [
     // Your other entities
     // UserEntity, ProductEntity, etc.

     // Dynamic entities from CrudConfigModule
     sectionEntity,
     dataEntity,
    ],
    synchronize: true,
   }),
  }),
 ],
})
export class AppModule {}

Using the Configuration Service

// config.service.ts
import { Injectable } from "@nestjs/common";
import { CrudConfigService } from "@elsikora/nestjs-crud-config";

@Injectable()
export class MyConfigService {
 constructor(private readonly configService: CrudConfigService) {}

 async setupApplicationConfig() {
  // Set a configuration value
  await this.configService.set({
   section: "api-settings",
   name: "API_KEY",
   value: "my-secret-api-key",
   description: "Production API key",
   environment: "production",
  });

  // Retrieve configuration by section and name
  const apiConfig = await this.configService.get({
   section: "api-settings",
   name: "API_KEY",
   environment: "production",
   shouldLoadSectionInfo: true,
   useCache: true,
  });

  console.log("API Configuration:", apiConfig);
  // apiConfig.value will be automatically decrypted if it was encrypted

  return apiConfig;
 }

 async getConfigurationList() {
  // Get all configurations in a section
  const configs = await this.configService.getList({
   section: "api-settings",
   environment: "production",
   useCache: true,
  });

  return configs;
 }

 async deleteConfiguration() {
  // Delete a configuration
  await this.configService.delete({
   section: "api-settings",
   name: "API_KEY",
   environment: "production",
  });
 }
}

Async Module Registration

When using registerAsync(), static options like controllers and entity configuration must be provided via the staticOptions property, as NestJS does not support async controller registration:

// app.module.ts
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { ApiAuthorizationModule } from "@elsikora/nestjs-crud-automator";
import { CrudConfigModule } from "@elsikora/nestjs-crud-config";

@Module({
 imports: [
  ApiAuthorizationModule,
  ConfigModule.forRoot(),
  CrudConfigModule.registerAsync({
   imports: [ConfigModule],
   inject: [ConfigService],
   // Dynamic options - resolved asynchronously
   useFactory: async (configService: ConfigService) => ({
    environment: configService.get("NODE_ENV", "development"),
    encryptionOptions: {
     isEnabled: true,
     encryptionKey: configService.get("ENCRYPTION_KEY"),
    },
    cacheOptions: {
     isEnabled: true,
     maxCacheItems: 1000,
     maxCacheTTL: 3600000,
    },
   }),
   // Static options - must be known at module registration time
   staticOptions: {
    controllersOptions: {
     section: {
      isEnabled: true,
      properties: {
       path: "api/config/sections",
      },
     },
     data: {
      isEnabled: true,
      properties: {
       path: "api/config/data",
      },
     },
    },
    entityOptions: {
     tablePrefix: "app_",
     timestampColumnType: "timestamptz", // Must be static for dynamic entities
     configSection: {
      tableName: "config_sections",
      maxNameLength: 128,
     },
     configData: {
      tableName: "config_data",
      maxValueLength: 8192,
     },
    },
    migrationEntityOptions: {
     tableName: "config_migrations",
    },
   },
  }),
 ],
})
export class AppModule {}

Important: The staticOptions property contains configuration that must be known at module compilation time:

  • controllersOptions - REST API controller configuration
  • entityOptions - Database entity customization (table names, field lengths, timestamp type)
  • migrationEntityOptions - Migration tracking table configuration

🚀 Migration System

The NestJS CRUD Config module includes a powerful production-ready migration system that allows you to initialize and manage configuration state during application startup. This system ensures your application always has the required configuration data across different environments and deployments.

Key Features

  • 🔄 Automatic execution on startup - Migrations run automatically when the application bootstraps
  • 💾 Named transaction support - Transaction-enabled migrations run inside one named Automator owner
  • 🌍 Environment-specific configurations - Create different configurations for different environments
  • 📊 Migration tracking - Complete audit trail with timestamps and execution status
  • 🔙 Rollback support - Define rollback procedures for each migration
  • ⚡ Stuck migration cleanup - Automatic timeout and cleanup of crashed migrations
  • 🎯 Type-safe status tracking - Uses EConfigMigrationStatus enum for reliable status management
  • 🛡️ Race condition protection - Thread-safe execution preventing concurrent conflicts

Migration Status Enum

The migration system uses the EConfigMigrationStatus enum to track migration states:

import { EConfigMigrationStatus } from "@elsikora/nestjs-crud-config";

// Available statuses:
EConfigMigrationStatus.PENDING; // Migration is pending execution
EConfigMigrationStatus.RUNNING; // Migration is currently running
EConfigMigrationStatus.COMPLETED; // Migration completed successfully
EConfigMigrationStatus.FAILED; // Migration failed with error
EConfigMigrationStatus.STUCK; // Migration is stuck (timeout)

Basic Migration Configuration

Configure migrations in your module registration:

import { CrudConfigModule } from "@elsikora/nestjs-crud-config";
import { initialAppConfigMigration } from "./migrations/001-initial-app-config.migration";

@Module({
 imports: [
  CrudConfigModule.register({
   environment: process.env.NODE_ENV || "development",

   // Migration configuration
   migrationOptions: {
    isEnabled: true,
    shouldRunOnStartup: true,
    useTransaction: true,
    stuckMigrationTimeoutMinutes: 30,
    tableName: "config_migrations", // Optional: custom table name

    migrations: [
     initialAppConfigMigration,
     // Add more migrations here
    ],
   },

   // Other configuration options...
  }),
 ],
})
export class AppModule {}

With useTransaction: true (the default), execution owns one crud-config-migrations transaction and passes its exact EntityManager to each migration callback. Pass that manager as eventManager to every config operation in the migration. Omitting it from set() would attempt to open the separate crud-config-set owner, and Automator rejects nested owners.

With useTransaction: false, there is no migration-wide owner and callbacks receive undefined. A standalone set() still owns its own atomic crud-config-set transaction, so several config writes are not one all-or-nothing unit. Rollback execution always uses the named migration owner.

Creating Migration Files

Create a migration file with the required structure:

// migrations/001-initial-app-config.migration.ts
import type { IConfigMigrationDefinition } from "@elsikora/nestjs-crud-config";
import type { CrudConfigService } from "@elsikora/nestjs-crud-config";
import type { EntityManager } from "typeorm";

export const initialAppConfigMigration: IConfigMigrationDefinition = {
 name: "001_initial_app_config",
 description: "Initialize basic application configuration",

 async up(configService: CrudConfigService, entityManager?: EntityManager): Promise<void> {
  // Create application settings
  await configService.set({
   section: "app-settings",
   name: "APP_NAME",
   value: "My Application",
   description: "Application name",
   environment: "default",
   eventManager: entityManager,
  });

  await configService.set({
   section: "app-settings",
   name: "APP_VERSION",
   value: "1.0.0",
   description: "Application version",
   environment: "default",
   eventManager: entityManager,
  });

  // Create API settings
  await configService.set({
   section: "api-settings",
   name: "API_RATE_LIMIT",
   value: "100",
   description: "API rate limit per minute",
   environment: "default",
   eventManager: entityManager,
  });
 },

 async down(configService: CrudConfigService, entityManager?: EntityManager): Promise<void> {
  // Rollback: remove configurations created by this migration
  const configurationsToRemove = [
   { name: "APP_NAME", section: "app-settings" },
   { name: "APP_VERSION", section: "app-settings" },
   { name: "API_RATE_LIMIT", section: "api-settings" },
  ];

  for (const config of configurationsToRemove) {
   try {
    await configService.delete({
     section: config.section,
     name: config.name,
     environment: "default",
     eventManager: entityManager,
    });
   } catch (error) {
    // Expected if config was never created
    console.warn(`Failed to delete config ${config.section}:${config.name} during rollback`);
   }
  }
 },
};

Environment-Specific Migrations

Create migrations that work with different environments:

// migrations/002-environment-specific-config.migration.ts
export const environmentSpecificConfigMigration: IConfigMigrationDefinition = {
 name: "002_environment_specific_config",
 description: "Environment-specific configuration settings",

 async up(configService: CrudConfigService, entityManager?: EntityManager): Promise<void> {
  const environments = ["development", "staging", "production"];

  for (const env of environments) {
   // Environment-specific debug settings
   await configService.set({
    section: "app-settings",
    name: "DEBUG_MODE",
    value: env === "development" ? "true" : "false",
    description: "Enable debug mode",
    environment: env,
    eventManager: entityManager,
   });

   // Environment-specific API limits
   const rateLimits = {
    development: "1000",
    staging: "500",
    production: "100",
   };

   await configService.set({
    section: "api-settings",
    name: "API_RATE_LIMIT",
    value: rateLimits[env],
    description: "API rate limit per minute",
    environment: env,
    eventManager: entityManager,
   });
  }
 },

 async down(configService: CrudConfigService, entityManager?: EntityManager): Promise<void> {
  const environments = ["development", "staging", "production"];
  const configurationsToRemove = [
   { name: "DEBUG_MODE", section: "app-settings" },
   { name: "API_RATE_LIMIT", section: "api-settings" },
  ];

  for (const config of configurationsToRemove) {
   for (const environment of environments) {
    try {
     await configService.delete({
      section: config.section,
      name: config.name,
      environment: environment,
      eventManager: entityManager,
     });
    } catch (error) {
     console.warn(
      `Failed to delete config ${config.section}:${config.name}:${environment} during rollback`,
     );
    }
   }
  }
 },
};

Advanced Migration Configuration

Configure migrations with custom options:

CrudConfigModule.registerAsync({
 imports: [ConfigModule],
 inject: [ConfigService],
 useFactory: async (configService: ConfigService) => ({
  environment: configService.get("NODE_ENV", "development"),

  migrationOptions: {
   isEnabled: true,
   shouldRunOnStartup: true,
   useTransaction: true,
   stuckMigrationTimeoutMinutes: 60, // Custom timeout

   migrations: [
    initialAppConfigMigration,
    environmentSpecificConfigMigration,
    // Add more migrations in order
   ],
  },

  // Other dynamic options...
 }),
 // Static options for entities and controllers
 staticOptions: {
  migrationEntityOptions: {
   tableName: "my_migrations", // Custom table name must be in staticOptions
   maxNameLength: 256,
  },
  controllersOptions: {
   section: { isEnabled: true },
   data: { isEnabled: true },
  },
 },
});

Migration Best Practices

  1. Naming Convention: Use descriptive names with sequence numbers

    • ✅ 001_initial_app_config
    • ✅ 002_add_feature_flags
    • ❌ migration1, config_setup
  2. Retry safety: Use set() as the upsert for a configuration key

    await configService.set({ eventManager: entityManager, ...properties });
    
  3. Error Handling: Always handle errors gracefully

    try {
     await configService.set({ eventManager: entityManager, ...properties });
    } catch (error) {
     console.error("Migration failed:", error);
     throw error; // Re-throw to mark migration as failed
    }
    
  4. Rollback Support: Always implement the down method

    async down(configService: CrudConfigService, entityManager?: EntityManager): Promise<void> {
      // Implement rollback logic
    }
    
  5. Environment Awareness: Use environment-specific configurations

    const currentEnv = process.env.NODE_ENV || "development";
    await configService.set({
     eventManager: entityManager,
     environment: currentEnv,
     // ... other options
    });
    

Migration Monitoring

Monitor migration execution with logging:

import { EConfigMigrationStatus } from "@elsikora/nestjs-crud-config";

@Injectable()
export class MigrationMonitorService {
 constructor(private readonly migrationService: ConfigMigrationService) {}

 async getMigrationStatus(): Promise<void> {
  const migrations = await this.migrationService.getExecutedMigrations();

  const completed = migrations.filter((m) => m.status === EConfigMigrationStatus.COMPLETED);
  const failed = migrations.filter((m) => m.status === EConfigMigrationStatus.FAILED);
  const stuck = migrations.filter((m) => m.status === EConfigMigrationStatus.STUCK);

  console.log(
   `Migrations - Completed: ${completed.length}, Failed: ${failed.length}, Stuck: ${stuck.length}`,
  );
 }

 async getFailedMigrations(): Promise<IConfigMigration[]> {
  const migrations = await this.migrationService.getExecutedMigrations();
  return migrations.filter((m) => m.status === EConfigMigrationStatus.FAILED);
 }
}

Testing Migrations

Test your migrations in different environments:

describe("Initial App Config Migration", () => {
 let configService: CrudConfigService;
 let migration: IConfigMigrationDefinition;

 beforeEach(async () => {
  // Setup test environment
  migration = initialAppConfigMigration;
 });

 it("should create required configurations", async () => {
  await migration.up(configService);

  const appName = await configService.get({
   section: "app-settings",
   name: "APP_NAME",
   environment: "default",
  });

  expect(appName.value).toBe("My Application");
 });

 it("should rollback configurations", async () => {
  await migration.up(configService);
  await migration.down(configService);

  await expect(
   configService.get({
    section: "app-settings",
    name: "APP_NAME",
    environment: "default",
   }),
  ).rejects.toThrow();
 });
});

📚 API Documentation

The module automatically generates REST API endpoints with customizable paths:

Configuration Sections (default: /config/section)

  • GET /config/section - List all sections
  • POST /config/section - Create a new section
  • GET /config/section/:id - Get section by ID
  • PUT /config/section/:id - Update section
  • DELETE /config/section/:id - Delete section

Request Body for POST/PUT:

{
 "name": "api-settings",
 "description": "API configuration settings"
}

Configuration Data (default: /config/data)

  • GET /config/data - List all configuration data
  • POST /config/data - Create new configuration
  • GET /config/data/:id - Get configuration by ID
  • PUT /config/data/:id - Update configuration
  • DELETE /config/data/:id - Delete configuration

Request Body for POST/PUT:

{
 "name": "API_KEY",
 "value": "your-secret-key",
 "environment": "production",
 "description": "Production API key",
 "isEncrypted": true,
 "section": { "id": "section-uuid-here" }
}

Customizing API Endpoints

CrudConfigModule.register({
 controllersOptions: {
  section: {
   properties: {
    path: "api/v1/settings/sections",
    name: "CustomSectionController",
    swagger: {
     tags: ["Configuration Sections"],
    },
   },
  },
  data: {
   properties: {
    path: "api/v1/settings/data",
    routes: {
     DELETE: { generation: { isEnabled: false } }, // Disable deletion
    },
   },
  },
 },
});

Automator route options use generation.isEnabled for route generation. Relation loading uses TypeORM relationLoadStrategy values ("query" or "join"); the built-in ConfigData section relation uses "query".

🗄️ Database Schema

The module creates two main tables with the following default structure:

Configuration Sections Table (config_section)

CREATE TABLE config_section (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name VARCHAR(128) NOT NULL UNIQUE,
  description VARCHAR(512),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Configuration Data Table (config_data)

CREATE TABLE config_data (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name VARCHAR(128) NOT NULL,
  value VARCHAR(8192) NOT NULL,
  environment VARCHAR(64) NOT NULL,
  description VARCHAR(512),
  is_encrypted BOOLEAN DEFAULT FALSE,
  section_id UUID NOT NULL REFERENCES config_section(id) ON DELETE CASCADE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE(name, environment, section_id)
);

🔧 Advanced Configuration

Encryption Support

The module provides built-in AES-256-GCM encryption for sensitive configuration values:

// Enable encryption with bounded derived-key reuse for repeated uncached reads
CrudConfigModule.register({
 cacheOptions: { isEnabled: false },
 encryptionOptions: {
  isEnabled: true,
  encryptionKey: process.env.CONFIG_ENCRYPTION_KEY, // 32+ character key
  derivedKeyCacheMaxEntries: 64,
 },
});

// When encryption is enabled, all values are encrypted automatically
await configService.set({
 section: "database",
 name: "DB_PASSWORD",
 value: "my-secret-password",
});

// Retrieve and decrypt automatically
const config = await configService.get({
 section: "database",
 name: "DB_PASSWORD",
 useCache: false,
});

console.log(config.value); // Automatically decrypted value
console.log(config.isEncrypted); // true

encryptionOptions.derivedKeyCacheMaxEntries bounds the number of derived keys retained by each module instance using lru-cache. Omit it or set it to 0 to disable reuse; a positive safe integer enables it. The same option is available through registerAsync().

This cache retains derived encryption keys in process memory, not configuration values. With useCache: false, each read still fetches the current database value, and every decrypt call authenticates the supplied ciphertext with AES-GCM. Only successful decryption populates or promotes a cache entry. Eviction, module destruction, or successful decryption with a different encryption key clears the affected key buffers. Encrypted storage format and the synchronous encryption API are unchanged.

Transaction and Duplicate Protection

CrudConfigService.set() owns a named Automator transaction when called without eventManager. When a migration supplies its owner manager, all generated ConfigSection and ConfigData service operations join that same transaction.

The package does not require consumer EventEmitterModule wiring. ConfigData uniqueness is enforced by the database across name, environment, and section; Automator maps a conflicting generated create or update to 409 CONFIGDATA_DUPLICATE_KEY. Put application-specific validation or auditing in the application service/lifecycle layer rather than a package before-insert event.

Headless Mode (Without Controllers)

CrudConfigModule.register({
 controllersOptions: {
  section: { isEnabled: false },
  data: { isEnabled: false },
 },
});

This is perfect for:

  • Background services that only need programmatic access
  • Microservices that manage config through message queues
  • Applications with custom GraphQL or gRPC interfaces

Working with Multiple Environments

// multi-env.service.ts
@Injectable()
export class MultiEnvironmentService {
 constructor(private readonly configService: CrudConfigService) {}

 async setupEnvironmentConfigs() {
  const environments = ["development", "staging", "production"];

  for (const env of environments) {
   await this.configService.set({
    section: "database",
    name: "DATABASE_URL",
    environment: env,
    value: `postgres://localhost:5432/${env}_db`,
    description: `Database URL for ${env} environment`,
   });
  }
 }
}

🛣 Roadmap

Task / FeatureStatus
Core dynamic entity system✅ Done
TypeORM integration with all databases✅ Done
Hierarchical configuration (sections/data)✅ Done
Full CRUD operations with REST API✅ Done
Swagger/OpenAPI documentation✅ Done
Multi-environment support✅ Done
Named Automator transaction ownership✅ Done
Caching system with TTL✅ Done
Custom table names and prefixes✅ Done
Validation and constraints✅ Done
NestJS CRUD Automator integration✅ Done
TypeScript interfaces and types✅ Done
AES-256-GCM encryption support✅ Done
Async module registration✅ Done
Auto-section creation✅ Done
GraphQL API endpoints🚧 In Progress
Configuration versioning and history🚧 In Progress
Role-based access control (RBAC)🚧 In Progress
Configuration templates and inheritance🚧 In Progress
Real-time configuration updates via WebSocket🚧 In Progress
Configuration validation schemas🚧 In Progress
Bulk import/export functionality🚧 In Progress
Configuration diff and merge tools🚧 In Progress
Audit logging and change tracking🚧 In Progress
Configuration backup and restore🚧 In Progress
Integration with external secret managers🚧 In Progress

❓ FAQ

What databases are supported?

The module supports any database that TypeORM supports, including:

  • PostgreSQL - Recommended for production
  • MySQL/MariaDB - Popular choice for web applications
  • SQLite - Perfect for development and testing (TypeORM 1 driver better-sqlite3)
  • Microsoft SQL Server - Enterprise database support
  • Oracle - Enterprise-grade database
  • MongoDB - NoSQL document database
  • CockroachDB - Distributed SQL database

How does this compare to environment variables?

While environment variables are great for simple configurations, this module provides:

  • Database persistence - Configurations survive container restarts
  • Runtime updates - Change configurations without redeployment
  • Hierarchical organization - Group related configurations
  • Multi-environment support - Manage dev/staging/prod from one place
  • Encryption support - Secure sensitive data
  • REST API - Manage configurations programmatically
  • Audit trails - Track configuration changes

Can I migrate from environment variables?

Yes! You can easily migrate by programmatically setting configurations during application startup:

async function migrateFromEnvVars() {
 const configs = [
  { section: "database", name: "DATABASE_URL", value: process.env.DATABASE_URL },
  { section: "api", name: "API_KEY", value: process.env.API_KEY },
  // ... more configurations
 ];

 for (const config of configs) {
  await configService.set(config);
 }
}

How do I handle sensitive configuration data?

The module provides built-in AES-256-GCM encryption support:

CrudConfigModule.register({
 encryptionOptions: {
  isEnabled: true,
  encryptionKey: process.env.CONFIG_ENCRYPTION_KEY,
 },
});

Sensitive values are automatically encrypted before storage and decrypted when retrieved.

Can I use this with microservices?

Absolutely! The module is perfect for microservice architectures:

  • Centralized configuration - All services can share the same config database
  • Service-specific sections - Organize configurations by service
  • Environment isolation - Separate dev/staging/prod configurations
  • Dynamic updates - Update configurations without service restarts

How do I customize table names and field sizes?

The module provides extensive customization options:

CrudConfigModule.register({
 entityOptions: {
  tablePrefix: "myapp_",
  timestampColumnType: "timestamptz",
  configSection: {
   tableName: "configuration_sections",
   maxNameLength: 256,
   maxDescriptionLength: 1024,
  },
  configData: {
   tableName: "configuration_values",
   maxValueLength: 16384, // 16KB values
   maxEnvironmentLength: 128,
   maxNameLength: 256,
   maxDescriptionLength: 1024,
  },
 },
});

timestampColumnType applies to all nine temporal columns in the section, data, and migration entities. It defaults to Date, which TypeORM maps to the timestamp type of each driver: timestamp on PostgreSQL and datetime on MySQL, MariaDB, SQLite (better-sqlite3) and SQL.js, so the default entities work on every one of them. Set a driver-specific type, such as "timestamptz" for PostgreSQL, only when the application needs it. Changing it for an existing database still requires the corresponding schema migration.

What happens if the database is unavailable?

The module includes caching to handle temporary database outages:

  • In-memory cache - Recently accessed configurations are cached
  • Configurable TTL - Control how long configurations are cached
  • Graceful degradation - Falls back to cached values when database is unavailable

Can I use this without REST API endpoints?

Yes! The module supports "headless mode" where controllers are disabled:

CrudConfigModule.register({
 controllersOptions: {
  section: { isEnabled: false },
  data: { isEnabled: false },
 },
});

Is this production-ready?

Yes! The module is built with production use in mind:

  • Type-safe - Full TypeScript support prevents runtime errors
  • Battle-tested - Built on proven technologies (NestJS, TypeORM)
  • Scalable - Works with enterprise databases
  • Secure - Built-in encryption and validation
  • Observable - Comprehensive logging and monitoring hooks

🔒 License

This project is licensed under MIT License

Copyright (c) 2025 ElsiKora

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

版本与发布记录

@elsikora/nestjs-crud-config 共发布 49 个版本,首次发布于 2025/07/14;过去 12 个月发布了 35 个版本。

版本发布日期距今
5.1.0latest2026/11/049 天前
5.1.0-dev.1beta2026/11/049 天前
5.0.02026/11/0310 天前
5.0.0-dev.62026/11/0310 天前
5.0.0-dev.52026/11/0211 天前
5.0.0-dev.42026/11/0211 天前

关于 @elsikora/nestjs-crud-config 的常见问题

@elsikora/nestjs-crud-config 是什么?

NestJS application configuration via database storage

如何安装 @elsikora/nestjs-crud-config?

在项目目录运行 npm install @elsikora/nestjs-crud-config,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:lodash(^4.18.1)、fastify(^5.12.7)、typeorm(^1.1.2)、@nestjs/core(^12.3.2)、@nestjs/common(^12.3.2)、@nestjs/swagger(^12.0.0)、@nestjs/typeorm(^12.0.1)、class-validator(^0.15.1)、@nestjs/passport(^12.0.0)、@nestjs/throttler(^6.7.1)、class-transformer(^0.5.1)、@nestjs/platform-fastify(^12.3.2)、@elsikora/nestjs-crud-automator(^5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@elsikora/nestjs-crud-config 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@elsikora/nestjs-crud-config 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@elsikora/nestjs-crud-config 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^22.13.0 || >=24.11.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@elsikora/nestjs-crud-config 可以商用吗?

@elsikora/nestjs-crud-config 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@elsikora/nestjs-crud-config 的下载量有多少?

根据 npm 官方下载统计,@elsikora/nestjs-crud-config 在 2026/10/14 – 2026/11/12 这 30 天内被下载 7,382 次,日均约 246 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@elsikora/nestjs-crud-config 还在维护吗?

最新版本 5.1.0 发布于 2026/11/04(9 天前);至今共发布 49 个版本,其中过去 12 个月发布了 35 个;首次发布于 2025/07/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。