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ần | Mô tả |
|---|---|
| Public Schema | Các model miền chính: người dùng, sản phẩm, merchant, tổ chức (30 model) |
| Pricing Schema | Giá vé, bộ giá, quy tắc giá, chi phí, thuế (7 model) |
| Allocation Schema | Chỗ 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 Schema | Quản lý tồn kho: hàng hóa, vị trí, theo dõi, đơn mua hàng (8 model) |
| Finance Schema | Ví tài chính, danh mục, giao dịch (3 model) |
| Payment Schema | Cấu hình webhook (1 model) |
| ERD | Sơ đồ Quan hệ Thực thể (Mermaid) |
| Migrations | CLI Migration, tích hợp Drizzle Kit, dữ liệu mẫu |
Tóm tắt Schema
| Schema | Model | Mô tả |
|---|---|---|
public | 30 | Miền chính: người dùng, sản phẩm, merchant, tổ chức, cấu hình |
pricing | 7 | Giá vé, bộ giá, quy tắc giá, chi phí, thuế, bộ thuế, loại thuế |
allocation | 4 | Chỗ ngồi sự kiện: bố cục, kế hoạch, đơn vị, khu vực |
sale | 2 | Đơn hàng bán và mục đơn hàng |
inventory | 8 | Quả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 |
finance | 3 | Ví tài chính, danh mục, giao dịch |
payment | 1 | Cấu hình webhook |
| Tổng | 55 |
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
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
@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ến | Mô tả |
|---|---|
APP_ENV_POSTGRES_HOST | Host cơ sở dữ liệu |
APP_ENV_POSTGRES_PORT | Cổng cơ sở dữ liệu |
APP_ENV_POSTGRES_DATABASE | Tên cơ sở dữ liệu |
APP_ENV_POSTGRES_USERNAME | Tên người dùng cơ sở dữ liệu |
APP_ENV_POSTGRES_PASSWORD | Mậ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ột | Kiểu | Mô tả |
|---|---|---|
id | text (PK) | Khóa chính Snowflake ID |
created_at | timestamptz | Thời gian tạo bản ghi |
modified_at | timestamptz | Thời gian cập nhật cuối cùng |
deleted_at | timestamptz | Thời gian xóa mềm (null = đang hoạt động) |
metadata | jsonb | Trường metadata linh hoạt (kiểu tùy theo model) |
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 createdAt và modifiedAt, 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.
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:
| Helper | Các Cột Tạo Ra | Sử dụng Bởi |
|---|---|---|
generateUserAuditColumnDefs() | created_by, modified_by | Organizer, Merchant, Configuration, SaleOrder, PurchaseOrder, v.v. |
generatePrincipalColumnDefs() | principal_id, principal_type | UserMapping, UserRole, ProductInfo, ProductIdentifier, TaxSet, v.v. |
generateDataTypeColumnDefs() | data_type, t_value, n_value, bo_value, b_value, j_value | FareRule, 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.
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.
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.
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 schemaindex.ts-- Barrel export
Tham khảo Framework IGNIS
- IGNIS DataSources -- BaseDataSource, decorator @datasource
- IGNIS Models -- BaseEntity, decorator @model, quan hệ
- IGNIS Repositories -- BaseRepository, decorator @repository, các thao tác CRUD