npm package: @hero-dynamic-form/typeorm-inspector
Description: TypeORM entity inspector adapter for @hero-dynamic-form/core
Author: hero-truong
Latest version: 1.0.49

# @hero-dynamic-form/typeorm-inspector

TypeORM entity inspector adapter for `@hero-dynamic-form/core`. This package provides both a library for runtime entity inspection and a CLI tool for generating/syncing TypeORM entities from your PostgreSQL database.

## Installation

```bash
npm install @hero-dynamic-form/typeorm-inspector
# or
pnpm add @hero-dynamic-form/typeorm-inspector
```

## CLI Usage

### Setup

Create a `.env` file in your project root with database connection settings:

```env
# Option 1: Use DATABASE_URL (connection string)
DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/your_database

# Option 2: Use individual env vars (if DATABASE_URL is not set)
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASS=postgres
DB_NAME=your_database
```

### Commands

#### List all tables

```bash
npx typeorm-inspector generate
```

Output:

```
Available tables:
  - users
  - posts
  - comments
```

#### Generate entity from table

```bash
npx typeorm-inspector generate <table_name> [options]
```

Options:

- `--output, -o <path>` - Output directory (default: `./src/entity`)
- `--force, -f` - Overwrite existing files
- `--env <path>` - Path to .env file (default: `.env`)

Example:

```bash
# Generate User entity from 'users' table
npx typeorm-inspector generate users -o ./src/datasource/entity

# Overwrite existing entity
npx typeorm-inspector generate users -o ./src/entity --force
```

Features:

- Automatically detects PostgreSQL enums and generates proper TypeORM enum decorators
- Checks for actual NULL values in data (not just schema) to correctly set `nullable: true`
- Converts snake_case column names to camelCase property names
- Handles special columns: `id` (PrimaryGeneratedColumn), `created_at`, `updated_at`

#### Sync entity with database

```bash
npx typeorm-inspector sync <entity_path> [options]
```

Options:

- `--apply` - Auto-apply fixes to entity file
- `--dry-run` - Preview changes without applying
- `--env <path>` - Path to .env file (default: `.env`)

Example:

```bash
# Compare entity with database schema
npx typeorm-inspector sync ./src/entity/User.ts

# Preview and apply fixes
npx typeorm-inspector sync ./src/entity/User.ts --apply
```

### Generated Entity Example

```typescript
import {
  BaseEntity,
  Column,
  Entity,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
} from "typeorm";

@Entity({ name: "users" })
export class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column({ type: "text" })
  username!: string;

  @Column({ type: "enum", enum: ["ADMIN", "USER"], enumName: "users_role" })
  role!: string;

  @Column({ type: "text", nullable: true })
  description?: string;

  @CreateDateColumn({ type: "timestamp", name: "created_at" })
  createdAt!: Date;

  @UpdateDateColumn({ type: "timestamp", name: "updated_at" })
  updatedAt!: Date;
}
```

## Library Usage

```typescript
import { DynamicFormCore } from "@hero-dynamic-form/core";
import { TypeORMEntityInspector } from "@hero-dynamic-form/typeorm-inspector";
import { User } from "./entities/User";

const inspector = new TypeORMEntityInspector();

const config = {
  resources: [
    {
      name: "users",
      entity: User,
    },
  ],
  entityInspector: inspector,
};

const core = new DynamicFormCore(config);
await core.init();
await core.start();
```

## Features

- Extracts TypeORM column metadata (type, nullable, enum, etc.)
- Generates validation rules from TypeORM decorators
- Supports class-validator decorators
- Works with all TypeORM column types
- CLI for generating entities from database schema
- CLI for syncing entities with database schema

## Environment Variables

Supports both `DATABASE_URL` connection string and individual environment variables:

| Variable       | Description                              | Default     |
| -------------- | ---------------------------------------- | ----------- |
| `DATABASE_URL` | Full connection string (takes priority)  | -           |
| `DB_HOST`      | Database host                            | `localhost` |
| `DB_PORT`      | Database port                            | `5432`      |
| `DB_USER`      | Database user                            | `postgres`  |
| `DB_PASS`      | Database password                        | `postgres`  |
| `DB_NAME`      | Database name                            | (required)  |

**Note:** If `DATABASE_URL` is set, it takes priority over individual variables.

## License

MIT