nestjs-config-validator
Version:
Advanced configuration validator for NestJS with type-safe schema validation
404 lines (339 loc) • 8.55 kB
Markdown
for NestJS with type-safe schema validation.
- ✅ **Type-safe validation** - Full TypeScript support with discriminated unions
- ✅ **Comprehensive validation** - String, number, boolean, object, and enum validation
- ✅ **Required field validation** - Check for missing required properties
- ✅ **Default value support** - Automatic application of default values
- ✅ **Environment variables support** - Read values from environment variables
- ✅ **Enum validation** - Validate enum values, default values, and examples
- ✅ **NestJS integration** - Ready-to-use with NestJS ConfigModule
- ✅ **Detailed error messages** - Clear validation error reporting
```bash
npm install nestjs-config-validator
```
Or add to your `package.json`:
```json
{
"dependencies": {
"nestjs-config-validator": "^1.0.0"
}
}
```
```typescript
import { RootConfigSchema } from 'nestjs-config-validator';
export const configSchema: RootConfigSchema = {
description: 'Application Configuration',
properties: [
{
name: 'database',
type: 'object',
properties: [
{
name: 'host',
type: 'string',
required: true,
description: 'Database host'
},
{
name: 'port',
type: 'number',
defaultValue: 5432,
min: 1,
max: 65535,
nodeEnv: 'DB_PORT'
},
{
name: 'ssl',
type: 'enum',
enum: ['disable', 'require', 'verify-ca', 'verify-full'],
defaultValue: 'disable'
}
]
},
{
name: 'redis',
type: 'object',
properties: [
{
name: 'host',
type: 'string',
required: true,
nodeEnv: 'REDIS_HOST'
},
{
name: 'port',
type: 'number',
defaultValue: 6379
}
]
}
]
};
```
```json
{
"database": {
"host": "localhost",
"port": 5432,
"ssl": "disable"
},
"redis": {
"host": "localhost",
"port": 6379
}
}
```
```typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { createNestJSConfiguration } from 'nestjs-config-validator';
import { configSchema } from './config.schema';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [() => createNestJSConfiguration(configSchema)],
cache: true,
}),
],
exports: [ConfigModule],
})
export class AppConfigModule {}
```
The package supports reading values from environment variables using the `nodeEnv` property:
```typescript
{
name: 'database',
type: 'object',
properties: [
{
name: 'host',
type: 'string',
required: true,
nodeEnv: 'DB_HOST', // Will read from process.env.DB_HOST
description: 'Database host'
},
{
name: 'port',
type: 'number',
defaultValue: 5432,
nodeEnv: 'DB_PORT', // Will read from process.env.DB_PORT
min: 1,
max: 65535
},
{
name: 'debug',
type: 'boolean',
defaultValue: false,
nodeEnv: 'DEBUG' // Will read from process.env.DEBUG
}
]
}
```
The validator follows this priority order when resolving values:
1. **Config file value** - Value explicitly set in config.json
2. **Environment variable** - Value from process.env (if `nodeEnv` is specified)
3. **Default value** - Value from `defaultValue` property
4. **undefined** - If none of the above are available
Environment variables are automatically converted to the appropriate type:
- **string**: Used as-is
- **number**: Parsed using `Number()`, invalid values become `undefined`
- **boolean**: Converted using `value.toLowerCase() === 'true'`
- **enum**: Used as-is (validation applied later)
```typescript
import { AdvancedConfigValidator } from 'nestjs-config-validator';
const validator = new AdvancedConfigValidator('./config.json');
const result = validator.validateRootSchema(configSchema);
if (!result.valid) {
console.error('Validation errors:', result.errors);
}
```
```typescript
import { AdvancedConfigValidator } from 'nestjs-config-validator';
const validator = new AdvancedConfigValidator();
const result = validator.validateSchema(databaseSchema, 'database');
if (!result.valid) {
console.error('Database validation errors:', result.errors);
}
```
```typescript
import { AdvancedConfigValidator } from 'nestjs-config-validator';
const validator = new AdvancedConfigValidator();
const config = validator.getValidatedConfig(databaseSchema, 'database');
// config contains validated data with applied default values
```
```typescript
{
name: 'apiKey',
type: 'string',
required: true,
minLength: 32,
maxLength: 64,
pattern: '^[A-Za-z0-9]+$',
nodeEnv: 'API_KEY' // Read from process.env.API_KEY
}
```
```typescript
{
name: 'port',
type: 'number',
defaultValue: 3000,
min: 1,
max: 65535,
nodeEnv: 'PORT' // Read from process.env.PORT
}
```
```typescript
{
name: 'debug',
type: 'boolean',
defaultValue: false,
nodeEnv: 'DEBUG' // Read from process.env.DEBUG
}
```
```typescript
{
name: 'environment',
type: 'enum',
enum: ['development', 'staging', 'production'],
defaultValue: 'development',
examples: ['development', 'production'],
nodeEnv: 'NODE_ENV' // Read from process.env.NODE_ENV
}
```
```typescript
{
name: 'database',
type: 'object',
properties: [
{
name: 'host',
type: 'string',
required: true,
nodeEnv: 'DB_HOST'
},
{
name: 'port',
type: 'number',
defaultValue: 5432,
nodeEnv: 'DB_PORT'
}
]
}
```
```typescript
// ❌ Error: wrong type
{
"database": {
"port": "5432" // should be number
}
}
// Error: Property 'database.port' must be a number, got string
// ✅ Correct
{
"database": {
"port": 5432
}
}
```
```typescript
// ❌ Error: value not in enum
{
"database": {
"ssl": "invalid" // should be one of the enum values
}
}
// Error: Property 'database.ssl' must be one of [disable, require, verify-ca, verify-full], got invalid
// ✅ Correct
{
"database": {
"ssl": "disable"
}
}
```
```typescript
// ❌ Error: missing required field
{
"database": {
"port": 5432
// missing host (required: true)
}
}
// Error: Required property 'database.host' is missing
// ✅ Correct
{
"database": {
"host": "localhost",
"port": 5432
}
}
```
The package provides seamless integration with NestJS:
```typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { createNestJSConfiguration } from 'nestjs-config-validator';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [() => createNestJSConfiguration(configSchema)],
cache: true,
}),
],
exports: [ConfigModule],
})
export class AppConfigModule {}
```
- Full TypeScript support
- Discriminated unions for strict typing
- IDE autocompletion
- All data type validation
- Enum value validation
- Required field checking
- Ready for ConfigModule integration
- Automatic validation on app startup
- Detailed error messages
- Easy to add new validation types
- Support for custom validators
- Flexible error system
MIT License - see LICENSE file for details.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## 📄 License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
Advanced configuration validator