Skip to content

Tổng quan Cơ sở dữ liệu

Gói @nx/core định nghĩa tất cả các model cơ sở dữ liệu trên 7 PostgreSQL schema với tổng cộng 55 model. Tất cả các gói chia sẻ một PostgresCoreDataSource duy nhất được hỗ trợ bởi Drizzle ORM với driver node-postgres.

Liên kết Nhanh

PhầnMô tả
Public SchemaCác model miền chính: người dùng, sản phẩm, merchant, tổ chức (30 model)
Pricing SchemaGiá vé, bộ giá, quy tắc giá, chi phí, thuế (7 model)
Allocation SchemaChỗ ngồi sự kiện: kế hoạch, bố cục, khu vực, đơn vị (4 model)
Sale SchemaĐơn hàng bán và mục đơn hàng bán (2 model)
Inventory SchemaQuản lý tồn kho: hàng hóa, vị trí, theo dõi, đơn mua hàng (8 model)
Finance SchemaVí tài chính, danh mục, giao dịch (3 model)
Payment SchemaCấu hình webhook (1 model)
ERDSơ đồ Quan hệ Thực thể (Mermaid)
MigrationsCLI Migration, tích hợp Drizzle Kit, dữ liệu mẫu

Tóm tắt Schema

SchemaModelMô tả
public30Miền chính: người dùng, sản phẩm, merchant, tổ chức, cấu hình
pricing7Giá vé, bộ giá, quy tắc giá, chi phí, thuế, bộ thuế, loại thuế
allocation4Chỗ ngồi sự kiện: bố cục, kế hoạch, đơn vị, khu vực
sale2Đơn hàng bán và mục đơn hàng
inventory8Quản lý tồn kho: hàng hóa, vị trí, tồn kho, theo dõi, đơn mua hàng, nhà cung cấp
finance3Ví tài chính, danh mục, giao dịch
payment1Cấu hình webhook
Tổng55

Phân bố schema trong cơ sở dữ liệu:

Tất cả 7 schema được định nghĩa trong lớp PostgresSchemas:

Nguồn: packages/core/src/common/constants.ts

typescript
export class PostgresSchemas {
  static readonly PUBLIC = 'public';
  static readonly PRICING = 'pricing';
  static readonly ALLOCATION = 'allocation';
  static readonly SALE = 'sale';
  static readonly INVENTORY = 'inventory';
  static readonly FINANCE = 'finance';
  static readonly PAYMENT = 'payment';

  static readonly SCHEME_SET = new Set([
    this.PUBLIC, this.PRICING, this.ALLOCATION,
    this.SALE, this.INVENTORY, this.FINANCE, this.PAYMENT,
  ]);
}

DataSource

Tất cả các gói kết nối đến cùng một cơ sở dữ liệu PostgreSQL thông qua PostgresCoreDataSource. Nó sử dụng driver node-postgres với Drizzle ORM và tự động phát hiện các model từ các binding @repository.

Nguồn: packages/core/src/datasources/postgres-core.datasource.ts

typescript
@datasource({ driver: 'node-postgres' })
export class PostgresCoreDataSource extends BaseDataSource<IPostgresDataSourceSettings> {
  override configure(): ValueOrPromise<void> {
    const schema = this.getSchema(); // Auto-discovers models from @repository bindings
    this.pool = new Pool(this.settings);
    this.connector = drizzle({ client: this.pool, schema });
  }

  override getConnectionString(): ValueOrPromise<string> {
    const { host, port, database, user, password, useSSL } = this.settings;
    return `postgresql://${user}:${password}@${host}:${port}/${database}?sslmode=${
      useSSL ? 'require' : 'disable'
    }`;
  }
}

Biến Môi trường

BiếnMô tả
APP_ENV_POSTGRES_HOSTHost cơ sở dữ liệu
APP_ENV_POSTGRES_PORTCổng cơ sở dữ liệu
APP_ENV_POSTGRES_DATABASETên cơ sở dữ liệu
APP_ENV_POSTGRES_USERNAMETên người dùng cơ sở dữ liệu
APP_ENV_POSTGRES_PASSWORDMật khẩu cơ sở dữ liệu

Để biết thêm chi tiết về data source trong framework IGNIS, xem Tham khảo IGNIS DataSources.

Định nghĩa Cột Chung

Tất cả các model chia sẻ một tập hợp cột chung được tạo bởi generateCommonColumnDefs(), định nghĩa trong packages/core/src/models/schemas/common.ts.

generateCommonColumnDefs()

Hàm này tạo ra các cột sau cho mọi model:

CộtKiểuMô tả
idtext (PK)Khóa chính Snowflake ID
created_attimestamptzThời gian tạo bản ghi
modified_attimestamptzThời gian cập nhật cuối cùng
deleted_attimestamptzThời gian xóa mềm (null = đang hoạt động)
metadatajsonbTrường metadata linh hoạt (kiểu tùy theo model)
typescript
export const generateCommonColumnDefs = <Metadata extends AnyType = AnyType>() => {
  return {
    ...generateIdColumnDefs({ id: { dataType: 'string' } }),
    ...generateTzColumnDefs({
      deleted: { enable: true, columnName: 'deleted_at', withTimezone: true },
    }),
    metadata: jsonb().$type<Metadata>(),
  };
};

Cột id sử dụng helper generateIdColumnDefs của IGNIS với kiểu dữ liệu string. ID được tạo bằng thuật toán Snowflake thông qua IdGenerator.

Helper generateTzColumnDefs tạo ra các mốc thời gian createdAtmodifiedAt, với cột deletedAt tùy chọn để hỗ trợ xóa mềm.

Kiểu isoTimestamp Tùy chỉnh

Các kiểu timestamp tích hợp của Drizzle có hành vi không tương thích:

  • mode: 'date' yêu cầu đối tượng Date (không thân thiện với JSON)
  • mode: 'string' trả về định dạng PostgreSQL thay vì ISO 8601

Kiểu tùy chỉnh isoTimestamp giải quyết vấn đề này bằng cách chấp nhận chuỗi ISO từ frontend và chuyển đổi timestamp PostgreSQL trở lại định dạng ISO 8601 để phản hồi API nhất quán.

typescript
export const isoTimestamp = (name: string, config?: { withTimezone?: boolean }) =>
  customType<{ data: string; driverData: string }>({
    dataType() {
      return `timestamp${config?.withTimezone ? ' with time zone' : ''}`;
    },
    toDriver(value: string): string {
      return value; // Pass the ISO string directly
    },
    fromDriver(value: string): string {
      const date = new Date(value);
      if (isNaN(date.getTime())) {
        throw getError({
          message: `Invalid date string: ${value}`,
          statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
        });
      }
      return date.toISOString(); // Always returns ISO 8601
    },
  })(name);

Các Helper Cột Bổ sung

Một số model cũng sử dụng các hàm tạo cột do IGNIS cung cấp:

HelperCác Cột Tạo RaSử dụng Bởi
generateUserAuditColumnDefs()created_by, modified_byOrganizer, Merchant, Configuration, SaleOrder, PurchaseOrder, v.v.
generatePrincipalColumnDefs()principal_id, principal_typeUserMapping, UserRole, ProductInfo, ProductIdentifier, TaxSet, v.v.
generateDataTypeColumnDefs()data_type, t_value, n_value, bo_value, b_value, j_valueFareRule, Configuration, Variant, UserConfiguration, Settings

Các Kiểu Chia sẻ

INameI18n

Các trường tên đa ngôn ngữ được lưu trữ dưới dạng JSONB với các bản dịch tiếng Anh và tiếng Việt tùy chọn.

typescript
export interface INameI18n {
  en?: string;
  vi?: string;
}

export const generateI18nColumnDef = (name: string) => jsonb(name).$type<INameI18n>();

Sử dụng cho: danh mục, vai trò, tổ chức, merchant, sản phẩm, tên giá vé, vị trí tồn kho, ví tài chính, và nhiều hơn.

ILocation

Địa chỉ vật lý và tọa độ được lưu trữ dưới dạng JSONB.

typescript
export interface ILocation {
  main: string;
  sub?: string;
  long?: string;
  lat?: string;
  postCode?: string;
}

Sử dụng cho: tổ chức, merchant, thiết bị, vị trí tồn kho, nhà cung cấp.

ISocial

Liên kết mạng xã hội được lưu trữ dưới dạng JSONB với các cặp khóa-giá trị mở rộng.

typescript
export interface ISocial {
  facebook?: string;
  twitter?: string;
  instagram?: string;
  linkedin?: string;
  [key: string]: string | undefined;
}

Sử dụng cho: tổ chức.

Cấu trúc Thư mục Schema

packages/core/src/models/schemas/
├── index.ts                        # Barrel export (tất cả schema)
├── common.ts                       # Kiểu chia sẻ, định nghĩa cột, đối tượng schema
├── public/                         # public schema (30 model)
│   ├── user/                       # User, UserProfile, UserIdentifier, v.v.
│   ├── role/                       # Role
│   ├── permission/                 # Permission, PermissionMapping
│   ├── organizer/                  # Organizer
│   ├── merchant/                   # Merchant, MerchantIdentifier
│   ├── product/                    # Product, ProductInfo, ProductVariant, v.v.
│   ├── category/                   # Category
│   ├── sale-channel/               # SaleChannel, SaleChannelProduct
│   ├── configuration/              # Configuration
│   ├── settings/                   # Settings
│   ├── device/                     # Device
│   ├── meta-link/                  # MetaLink
│   ├── campaign/                   # Campaign
│   ├── quota/                      # Quota
│   ├── email-verification/         # EmailVerification
│   └── migration/                  # Migration
├── pricing/                        # pricing schema (7 model)
├── allocation/                     # allocation schema (4 model)
├── sale/                           # sale schema (2 model)
├── inventory/                      # inventory schema (8 model)
├── finance/                        # finance schema (3 model)
└── payment/                        # payment schema (1 model)

Mỗi thư mục model chứa:

  • schema.ts -- Định nghĩa bảng Drizzle (cột, chỉ mục, ràng buộc)
  • model.ts -- Lớp Entity với decorator @model, quan hệ, và Zod schema
  • index.ts -- Barrel export

Tham khảo Framework IGNIS

Proprietary and Confidential. Unauthorized copying, distribution, or use of this software is strictly prohibited.