npm package: @takepack/core
Description: A comprehensive NestJS library providing dynamic configuration management with Zod validation, TypeORM database support, migration management, seeding capabilities, and type-safe event handling
Author: hieutran03
Latest version: 1.0.2

# @takepack/core

> A comprehensive NestJS utility library providing configuration management, database operations, and event handling - all in one package.

[![npm version](https://img.shields.io/npm/v/@takepack/core.svg)](https://www.npmjs.com/package/@takepack/core)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.7+-blue.svg)](https://www.typescriptlang.org/)
[![NestJS](https://img.shields.io/badge/NestJS-10%20%7C%2011-red.svg)](https://nestjs.com/)

## 📦 What's Inside

This package combines three powerful modules for NestJS applications:

- **🔧 Config Module** - Dynamic configuration management with Zod validation
- **🗄️ Database Module** - TypeORM integration with migrations and seeding
- **📡 Event Module** - Type-safe event handling system

## 🚀 Quick Start

### Installation

```bash
npm install @takepack/core
```

### Peer Dependencies

```bash
npm install @nestjs/common @nestjs/core @nestjs/config reflect-metadata rxjs zod

# Optional (for database features)
npm install @nestjs/typeorm typeorm

# Optional (for event features)
npm install @nestjs/event-emitter
```

## 📚 Modules Overview

### 1. Config Module

Dynamic configuration management with automatic loading, Zod validation, and CLI code generation.

**Key Features:**
- ✅ Automatic config file loading (`*.config.ts`)
- ✅ Zod schema validation for environment variables
- ✅ CLI for generating config templates
- ✅ Type-safe configuration access
- ✅ Support for multiple environments

**Quick Example:**

```typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@takepack/core';

@Module({
  imports: [
    ConfigModule.register({
      configDir: 'src/configs',
      envFilePath: '.env',
      validate: true,
    }),
  ],
})
export class AppModule {}
```

**CLI Usage:**

```bash
# Generate all default configs
npx take-config generate --output src/configs --all

# Generate specific configs
npx take-config generate -o src/configs -c app database

# Generate custom config
npx take-config generate -o src/configs -i payment
```

[📖 Full Config Documentation](src/config/README.md)

---

### 2. Database Module

Comprehensive TypeORM integration with migration management, seeding system, and CLI commands.

**Key Features:**
- ✅ Migration generation and management
- ✅ Factory pattern for test data
- ✅ Array-based seeder system with ordering
- ✅ CLI commands for database operations
- ✅ Transaction support
- ✅ Auto-run capabilities

**Quick Example:**

```typescript
import { Module } from '@nestjs/common';
import { DatabaseExtensionModule, DatabaseType } from '@takepack/core';

@Module({
  imports: [
    DatabaseExtensionModule.registerAsync({
      useFactory: (config: ConfigService) => ({
        connection: {
          type: DatabaseType.POSTGRES,
          host: config.get('DB_HOST'),
          port: config.get('DB_PORT'),
          username: config.get('DB_USERNAME'),
          password: config.get('DB_PASSWORD'),
          database: config.get('DB_DATABASE'),
        },
        migration: {
          enabled: true,
          migrationsPath: 'src/migrations',
          autoRun: false,
        },
        seeder: {
          enabled: true,
          seeds: [InitialSeeder, UserSeeder],
          autoRun: false,
        },
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}
```

**CLI Usage:**

```bash
# Migration commands
npm run cli migration generate CreateUsersTable
npm run cli migration run
npm run cli migration revert

# Seeding commands
npm run cli seed                          # Run all seeders
npm run cli seed -- UserSeeder            # Run specific seeder
npm run cli seed -- --transaction each    # Transaction per seeder
```

[📖 Full Database Documentation](src/database/README.md)

---

### 3. Event Module

Type-safe event handling with a clean abstraction over `@nestjs/event-emitter`.

**Key Features:**
- ✅ Type-safe event classes instead of strings
- ✅ Decorator-based API
- ✅ Event Bus pattern
- ✅ Auto-completion and refactoring support
- ✅ Zero additional dependencies

**Quick Example:**

```typescript
// 1. Define Event
import { Event } from '@takepack/core';

@Event('user.created')
export class UserCreatedEvent {
  constructor(
    public readonly userId: string,
    public readonly email: string,
  ) {}
}

// 2. Publish Event
import { EventBus } from '@takepack/core';

@Injectable()
export class UserService {
  constructor(private eventBus: EventBus) {}

  async createUser(data: CreateUserDto) {
    const user = await this.userRepository.save(data);
    this.eventBus.publish(new UserCreatedEvent(user.id, user.email));
    return user;
  }
}

// 3. Handle Event
import { OnEventClass } from '@takepack/core';

@Injectable()
export class UserCreatedListener {
  @OnEventClass(UserCreatedEvent)
  async handleUserCreated(event: UserCreatedEvent) {
    console.log(`User ${event.email} created`);
  }
}

// 4. Register Module
@Module({
  imports: [EventsModule],
})
export class AppModule {}
```

[📖 Full Event Documentation](src/event/README.md)

---

## 🎯 Complete Example

Here's how to use all three modules together in a NestJS application:

```typescript
import { Module } from '@nestjs/common';
import { 
  ConfigModule, 
  DatabaseExtensionModule, 
  EventsModule,
  DatabaseType 
} from '@takepack/core';

@Module({
  imports: [
    // Config Module
    ConfigModule.register({
      configDir: 'src/configs',
      envFilePath: '.env',
      validate: true,
    }),

    // Database Module
    DatabaseExtensionModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        connection: {
          type: DatabaseType.POSTGRES,
          host: config.get('database').host,
          port: config.get('database').port,
          username: config.get('database').username,
          password: config.get('database').password,
          database: config.get('database').database,
        },
        entities: ['dist/**/*.entity{.ts,.js}'],
        migration: {
          enabled: true,
          migrationsPath: 'src/migrations',
          autoRun: process.env.NODE_ENV === 'development',
        },
        seeder: {
          enabled: true,
          seeds: [InitialSeeder],
          autoRun: false,
        },
      }),
      global: true,
    }),

    // Event Module
    EventsModule,
  ],
})
export class AppModule {}
```

## 📦 Exports

### Config Module
```typescript
export { ConfigModule, ConfigService, ConfigHelpers } from '@takepack/core';
```

### Database Module
```typescript
export { 
  DatabaseExtensionModule,
  DatabaseCommandModule,
  MigrationService,
  SeederService,
  BaseFactory,
  Seeder,
  DatabaseType,
  DatabaseModuleConfig,
} from '@takepack/core';
```

### Event Module
```typescript
export { 
  EventsModule,
  EventBus,
  Event,
  OnEventClass,
} from '@takepack/core';
```

## 🛠️ Development

### Build

```bash
npm run build
```

### Test

```bash
npm test
npm run test:watch
npm run test:cov
```

### Lint & Format

```bash
npm run lint
npm run format
```

## 📋 Requirements

- Node.js >= 16.0.0
- NestJS >= 10.0.0
- TypeScript >= 5.0.0

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## 📄 License

MIT © [hieutran03](https://github.com/hieutran03)

## 🔗 Links

- [GitHub Repository](https://github.com/hieutran03/takeuchi-pack)
- [Issue Tracker](https://github.com/hieutran03/takeuchi-pack/issues)
- [NPM Package](https://www.npmjs.com/package/@takepack/core)

## 📖 Documentation

- [Config Module Guide](src/config/README.md)
- [Database Module Guide](src/database/README.md)
- [Event Module Guide](src/event/README.md)

---

Made with ❤️ by [hieutran03](https://github.com/hieutran03)