# @nest-omni/core

A comprehensive NestJS framework for building enterprise-grade applications with best practices, decorators, validators, filters, interceptors, and utilities.

## Features

- 🎯 **Rich Decorators**: Custom decorators for controllers, routes, validation, and more
- 🛡️ **Advanced Filters**: Global exception handling with customizable error responses
- 🔄 **Interceptors**: Request/response transformation, logging, and translation
- ✅ **Validators**: Custom validators for common use cases (phone numbers, emails, etc.)
- 🏥 **Health Checks**: Built-in health checker module with configurable endpoints
- 🔧 **Middleware**: Compression, logging, and session management
- 📦 **Bootstrap Utilities**: Easy application setup with PM2 support and different modes
- 🌍 **i18n Support**: Internationalization with nestjs-i18n integration
- 🔒 **Redis Lock**: Distributed locking mechanism with decorators
- 📊 **Audit**: Request auditing and logging capabilities
- 🔐 **Sentry Integration**: Built-in error tracking and performance monitoring
- 🚀 **TypeScript 5.9+**: Full support for latest TypeScript features
- 📦 **Zero Config**: Most dependencies bundled - minimal setup required

## Installation

```bash
npm install @nest-omni/core

# Essential peer dependencies (required)
npm install @nestjs/common@^11.0.0 @nestjs/core@^11.0.0 @nestjs/platform-express@^11.0.0

# Optional peer dependencies (install as needed)
npm install typeorm@^0.3.20 @nestjs/typeorm@^11.0.0  # For database
npm install @nestjs/swagger@^11.0.0  # For API documentation
npm install @nestjs/schedule@^6.0.0  # For scheduled tasks
npm install nestjs-i18n@^10.5.0  # For internationalization
```

## Requirements

- Node.js >= 18.0.0
- NestJS >= 11.0.0
- TypeScript >= 5.9.0

## What's New in v3.1.0

- ✨ **Updated Dependencies**: All dependencies upgraded to latest stable versions
- 📦 **Better Bundling**: Core runtime dependencies now bundled (axios, lodash, moment, etc.)
- 🎯 **Enhanced Exports**: Sub-path exports for better tree-shaking
- 🔧 **Improved Types**: Better TypeScript support with updated type definitions
- 🚀 **NestJS 11**: Full support for NestJS 11.x
- 📊 **Sentry 10**: Upgraded to latest Sentry SDK with improved performance monitoring

## Quick Start

### 1. Basic Setup

```typescript
import { Module } from '@nestjs/common';
import { HealthCheckerModule } from '@nest-omni/core';

@Module({
  imports: [HealthCheckerModule],
})
export class AppModule {}
```

### 2. Using Bootstrap

```typescript
import { bootstrap } from '@nest-omni/core';
import { AppModule } from './app.module';

bootstrap(AppModule, {
  port: 3000,
  globalPrefix: 'api',
  enableCors: true,
  enableSwagger: true,
});
```

### 3. Using Decorators

```typescript
import { Controller, Get } from '@nestjs/common';
import { ApiController, ApiOperation, PublicRoute } from '@nest-omni/core';

@ApiController('users', 'User Management')
@Controller('users')
export class UsersController {
  @Get()
  @PublicRoute()
  @ApiOperation({ summary: 'Get all users' })
  findAll() {
    return [];
  }
}
```

## Sub-path Exports

The package now supports sub-path exports for better tree-shaking and smaller bundle sizes:

```typescript
// Import from main entry (includes everything)
import { ApiController, QueryFailedFilter } from '@nest-omni/core';

// Import from specific sub-paths (better tree-shaking)
import { ApiController } from '@nest-omni/core/decorators';
import { QueryFailedFilter } from '@nest-omni/core/filters';
import { TranslationInterceptor } from '@nest-omni/core/interceptors';
import { IsPhoneNumber } from '@nest-omni/core/validators';
import { bootstrap } from '@nest-omni/core/setup';
import { HealthCheckerModule } from '@nest-omni/core/health-checker';
```

Available sub-paths:
- `@nest-omni/core` - Main entry point (all exports)
- `@nest-omni/core/decorators` - Decorators only
- `@nest-omni/core/filters` - Exception filters only
- `@nest-omni/core/interceptors` - Interceptors only
- `@nest-omni/core/validators` - Custom validators only
- `@nest-omni/core/setup` - Bootstrap and setup utilities
- `@nest-omni/core/health-checker` - Health check module

## Core Modules

### Decorators

#### Controller Decorators
- `@ApiController(path, tag)` - Enhanced API controller with Swagger tags
- `@PublicRoute()` - Mark route as public (skip authentication)

#### Property Decorators
- `@NumberField(options)` - Number field with validation
- `@StringField(options)` - String field with validation
- `@BooleanField(options)` - Boolean field with validation
- `@DateField(options)` - Date field with validation
- `@EmailField(options)` - Email field with validation
- `@PhoneField(options)` - Phone number field with validation
- `@UrlField(options)` - URL field with validation

#### User Decorator
- `@User()` - Extract user from request

#### Transform Decorators
- `@Trim()` - Trim string values
- `@ToLowerCase()` - Convert to lowercase
- `@ToUpperCase()` - Convert to uppercase

### Filters

Global exception filters for handling common errors:

```typescript
import { BadRequestExceptionFilter, QueryFailedFilter } from '@nest-omni/core';

app.useGlobalFilters(
  new BadRequestExceptionFilter(),
  new QueryFailedFilter(),
);
```

### Interceptors

#### LanguageInterceptor
Handles language detection and setting:

```typescript
import { LanguageInterceptor } from '@nest-omni/core';

app.useGlobalInterceptors(new LanguageInterceptor());
```

#### TranslationInterceptor
Handles response translation:

```typescript
import { TranslationInterceptor } from '@nest-omni/core';

app.useGlobalInterceptors(new TranslationInterceptor());
```

### Validators

Custom validators for common use cases:

```typescript
import { IsPhoneNumber, IsEmail, IsUrl } from '@nest-omni/core';

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsPhoneNumber()
  phone: string;

  @IsUrl()
  website: string;
}
```

### Health Checker

Built-in health check endpoint:

```typescript
import { HealthCheckerModule } from '@nest-omni/core';

@Module({
  imports: [
    HealthCheckerModule, // Adds /health endpoint
  ],
})
export class AppModule {}
```

### Setup & Bootstrap

#### Mode-based Setup

Support for different execution modes (web, worker, scheduler):

```typescript
import { ModeSetup } from '@nest-omni/core';

const mode = ModeSetup.getMode(); // 'web' | 'worker' | 'scheduler'
```

#### Worker Decorator

```typescript
import { Worker } from '@nest-omni/core';

export class TaskService {
  @Worker()
  async processTask() {
    // This will only run in worker mode
  }
}
```

#### Schedule Decorator

```typescript
import { Schedule } from '@nest-omni/core';

export class SchedulerService {
  @Schedule()
  @Cron('0 0 * * *')
  async dailyTask() {
    // This will only run in scheduler mode
  }
}
```

#### Redis Lock

分布式锁服务，支持装饰器和服务注入两种使用方式：

```typescript
import { RedisLockModule, UseRedisLock, RedisLockService } from '@nest-omni/core';

// 模块配置
@Module({
  imports: [
    RedisLockModule.forRootAsync({
      imports: [RedisModule],
      inject: [RedisService],
      useFactory: (redisService: RedisService) => ({
        redisClient: redisService.getClient(),
      }),
    }),
  ],
})

// 使用装饰器（推荐）
@Cron('0 * * * *')
@UseRedisLock('hourly-task', { ttl: 3600000 })
async hourlyTask() {
  // 在分布式环境下，同一时间只有一个实例会执行
}

// 使用服务注入
async processOrder(orderId: string) {
  const lockResult = await this.lockService.acquireLock(
    `order:${orderId}`,
    { ttl: 60000 }
  );

  if (!lockResult.acquired) return;

  try {
    await this.doProcess(orderId);
  } finally {
    await this.lockService.releaseLock(
      `order:${orderId}`,
      lockResult.lockValue
    );
  }
}
```

**[📖 查看完整文档](./src/redis-lock/README.md)**

### Cache System

企业级三层缓存架构，支持智能依赖管理：

```typescript
import { CacheModule, Cacheable, TagDependency } from '@nest-omni/core';

// 模块配置
@Module({
  imports: [
    CacheModule.forRoot({
      redis: { host: 'localhost', port: 6379 },
      defaultTtl: 300000, // 5分钟
    }),
  ],
})

// 使用装饰器（推荐）
@Cacheable({
  key: (id: string) => `user:${id}`,
  ttl: 300000,
  dependencies: [new TagDependency(['user-data'])],
})
async getUser(id: string): Promise<User> {
  return await this.userRepository.findOne(id);
}

// 使用服务
async getProduct(id: string): Promise<Product> {
  return await this.cacheService.getOrSet(
    `product:${id}`,
    () => this.productRepository.findOne(id),
    { ttl: 600000 }
  );
}
```

**核心特性：**
- 🏗️ 三层缓存架构（CLS + Memory + Redis）
- 🔗 6种智能依赖类型（Tag, DB, Callback, Chain, File, Time）
- 🎯 装饰器支持（@Cacheable, @CacheEvict, @CachePut）
- 📊 性能监控和统计
- 🛡️ 自动回填机制

**[📖 查看完整文档](./src/cache/README.md)**



## Middleware

### Compression Middleware

Automatically enabled in production:

```typescript
import { setupCompression } from '@nest-omni/core';

const app = await NestFactory.create(AppModule);
setupCompression(app);
```

## Configuration

### TypeScript Configuration

Your `tsconfig.json`:

```json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "ES2022",
    "module": "commonjs"
  }
}
```

## Advanced Usage

### Custom Exception Handling

```typescript
import { HttpException, HttpStatus } from '@nestjs/common';
import { BaseExceptionFilter } from '@nest-omni/core';

@Catch()
export class CustomExceptionFilter extends BaseExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    // Your custom logic
    super.catch(exception, host);
  }
}
```

### Integration with i18n

```typescript
import { I18nModule } from 'nestjs-i18n';

@Module({
  imports: [
    I18nModule.forRoot({
      fallbackLanguage: 'en',
      loaderOptions: {
        path: path.join(__dirname, '/i18n/'),
        watch: true,
      },
    }),
  ],
})
export class AppModule {}
```

## PM2 Deployment

The framework includes PM2 support for production deployments:

```typescript
import { bootstrap } from '@nest-omni/core';

bootstrap(AppModule, {
  pm2: true,
  instances: 4, // or 'max'
});
```

## License

Apache-2.0 © Jinpy

## Support

- Email: jinpy.he@kuehne-nagel.com

## Credits

Built with ❤️ using:
- [NestJS](https://nestjs.com/)
- [TypeORM](https://typeorm.io/)
- [class-validator](https://github.com/typestack/class-validator)
- [class-transformer](https://github.com/typestack/class-transformer)
