Skip to content

Bootstrap Helpers

Tổng quan

Gói @nx/core cung cấp ba tiện ích bootstrap chuẩn hóa cách mỗi dịch vụ BANA khởi chạy và cách migration cơ sở dữ liệu được thực thi. Các helper này đóng gói vòng đời ứng dụng IGNIS, xử lý lỗi đồng nhất và đảm bảo mọi gói tuân theo cùng trình tự khởi tạo.

HelperMục đíchNguồn
bootstrapApplicationKhởi chạy một HTTP servicesrc/helpers/bootstraps/application.ts
bootstrapMigrationChạy các quy trình seed/migration cơ sở dữ liệusrc/helpers/bootstraps/migration.ts
createMigrationProcessLoaderImport động các tệp quy trình migrationsrc/helpers/migration/process-loader.ts
MigrationHelperThực thi các pha cleanup và migrate với theo dõi trạng tháisrc/helpers/migration/helper.ts

bootstrapApplication

Tạo, khởi tạo, boot và khởi chạy một ứng dụng IGNIS. Khi thành công, nó tùy chọn in banner ASCII. Khi thất bại, nó ghi log lỗi và thoát process với mã 1.

Chữ ký

typescript
bootstrapApplication(opts: {
  ApplicationClass: new (opts: {
    scope: string;
    config: IApplicationConfigs;
  }) => DefaultApplication;
  config: IApplicationConfigs;
  options?: { bannerPath?: string };
}): Promise<void>

Tham số

Tham sốKiểuBắt buộcMô tả
ApplicationClassConstructor của DefaultApplicationLớp ứng dụng để khởi tạo
configIApplicationConfigsHost server, port, đường dẫn cơ sở, tùy chọn boot
options.bannerPathstringKhôngĐường dẫn tuyệt đối đến tệp banner ASCII được in sau khi khởi chạy thành công

Trình tự Vòng đời

Cách sử dụng

Mỗi điểm khởi đầu gói (src/index.ts) tuân theo cùng mẫu:

typescript
// packages/sale/src/index.ts
import { bootstrapApplication } from '@nx/core';
import { resolve } from 'node:path';
import { appConfig, Application } from './application';

bootstrapApplication({
  ApplicationClass: Application,
  config: appConfig,
  options: { bannerPath: resolve(process.cwd(), 'resources/banner.txt') },
});

bootstrapMigration

Tạo một instance ứng dụng tối thiểu đủ để kết nối cơ sở dữ liệu, đăng ký MigrationRepository, và chạy tất cả quy trình migration thông qua MigrationHelper.

Chữ ký

typescript
bootstrapMigration(opts: {
  ApplicationClass: new (opts: {
    scope: string;
    config: IApplicationConfigs;
  }) => DefaultApplication;
  getMigrationProcesses: () => Promise<TMigrationProcess[]>;
}): Promise<void>

Tham số

Tham sốKiểuBắt buộcMô tả
ApplicationClassConstructor của DefaultApplicationLớp ứng dụng (cùng lớp dùng để phục vụ)
getMigrationProcesses() => Promise<TMigrationProcess[]>Hàm trả về mảng định nghĩa quy trình migration

Trình tự Vòng đời

Cách sử dụng

Mỗi điểm khởi đầu migration của gói (src/migrate.ts) tuân theo mẫu này:

typescript
// packages/sale/src/migrate.ts
import { bootstrapMigration } from '@nx/core';
import { Application } from './application';
import { getMigrationProcesses } from './migrations/processes/migration-process';

bootstrapMigration({
  ApplicationClass: Application,
  getMigrationProcesses,
})
  .then(() => {
    process.exit(0);
  })
  .catch(err => {
    console.error('Cannot migrate database schema', err);
    process.exit(1);
  });

createMigrationProcessLoader

Hàm factory trả về một hàm bất đồng bộ để import động các tệp quy trình migration. Mỗi tệp phải export một TMigrationProcess dưới dạng default export. Các tệp không import được hoặc thiếu default export sẽ bị bỏ qua im lặng.

Chữ ký

typescript
createMigrationProcessLoader(opts: {
  seedPaths: string[];
  importFn: (path: string) => Promise<any>;
}): () => Promise<TMigrationProcess[]>

Tham số

Tham sốKiểuBắt buộcMô tả
seedPathsstring[]Danh sách có thứ tự tên tệp migration (không có phần mở rộng)
importFn(path: string) => Promise<any>Hàm import động giải quyết đường dẫn tệp

Cách sử dụng

typescript
// packages/payment/src/migrations/processes/migration-process.ts
import { createMigrationProcessLoader } from '@nx/core';

export const getMigrationProcesses = createMigrationProcessLoader({
  seedPaths: [
    'payment-0001-seed-vnpay-qr-mms-configuration',
    'payment-0002-seed-vnpay-phone-pos-configuration',
  ],
  importFn: path => import(`../processes/${path}.js`),
});

Các gói không có dữ liệu seed truyền mảng rỗng:

typescript
// packages/sale/src/migrations/processes/migration-process.ts
import { createMigrationProcessLoader } from '@nx/core';

export const getMigrationProcesses = createMigrationProcessLoader({
  seedPaths: [],
  importFn: path => import(`../processes/${path}.js`),
});

TMigrationProcess

Định nghĩa kiểu cho một quy trình migration đơn lẻ.

Định nghĩa Kiểu

typescript
type TMigrationProcess<
  ExtraOptionsType extends { alwaysRun?: boolean } = { alwaysRun?: boolean },
> = {
  name: string;
  cleanFn?: (opts: { context: BaseApplication }) => ValueOrPromise<void>;
  migrateFn: (opts: { context: BaseApplication }) => ValueOrPromise<void>;
  options?: ExtraOptionsType;
};

Các Trường

TrườngKiểuBắt buộcMô tả
namestringĐịnh danh migration duy nhất, được lưu trong bảng Migration
cleanFn(opts) => voidKhôngHàm dọn dẹp được gọi trước migration (ví dụ: xóa dữ liệu cũ)
migrateFn(opts) => voidLogic migration (seed dữ liệu, thay đổi schema, v.v.)
options.alwaysRunbooleanKhôngKhi true, chạy lại ngay cả khi đã được ghi nhận là SUCCESS trước đó

Viết một Quy trình Migration

typescript
// packages/payment/src/migrations/processes/payment-0001-seed-vnpay-qr-mms-configuration.ts
import { TMigrationProcess } from '@nx/core';

const process: TMigrationProcess = {
  name: 'payment-0001-seed-vnpay-qr-mms-configuration',
  migrateFn: async ({ context }) => {
    const repository = context.get({ key: 'repositories.ConfigurationRepository' });
    await repository.create({
      data: {
        key: 'VNPAY_QR_MMS',
        value: JSON.stringify({ /* provider config */ }),
      },
    });
  },
};

export default process;

MigrationHelper

Điều phối toàn bộ quy trình migration: dọn dẹp tiếp theo là migration. Nó theo dõi trạng thái của mỗi migration (SUCCESS hoặc FAIL) trong bảng cơ sở dữ liệu Migration và hỗ trợ các hook vòng đời.

Quy trình Làm việc

Các Hook Migration

Các hook cho phép mã bên ngoài quan sát hoặc mở rộng vòng đời migration:

typescript
type TMigrationHooks = {
  beforeCleanup?: (opts: { context: BaseApplication; processes: TMigrationProcess[] }) => void;
  afterCleanup?: (opts: { context: BaseApplication; processes: TMigrationProcess[] }) => void;
  beforeMigration?: (opts: { context: BaseApplication; processes: TMigrationProcess[] }) => void;
  afterMigration?: (opts: { context: BaseApplication; processes: TMigrationProcess[] }) => void;
  onMigrationSuccess?: (opts: { name: string; process: TMigrationProcess; duration: number }) => void;
  onMigrationError?: (opts: { name: string; process: TMigrationProcess; error: unknown }) => void;
};
HookThời điểmNhận được
beforeCleanupTrước khi pha dọn dẹp bắt đầuNgữ cảnh ứng dụng, tất cả quy trình
afterCleanupSau khi tất cả hàm dọn dẹp hoàn thànhNgữ cảnh ứng dụng, tất cả quy trình
beforeMigrationTrước khi pha migration bắt đầuNgữ cảnh ứng dụng, tất cả quy trình
afterMigrationSau khi tất cả hàm migration hoàn thànhNgữ cảnh ứng dụng, tất cả quy trình
onMigrationSuccessSau khi một quy trình đơn lẻ thành côngTên quy trình, định nghĩa quy trình, thời lượng (ms)
onMigrationErrorSau khi một quy trình đơn lẻ thất bạiTên quy trình, định nghĩa quy trình, lỗi

Tất cả hook được bọc trong try/catch nội bộ. Hook thất bại sẽ ghi log cảnh báo nhưng không dừng migration.

Theo dõi Trạng thái

MigrationHelper sử dụng MigrationRepository (được đăng ký tự động bởi bootstrapMigration) để lưu trữ kết quả của mỗi quy trình:

Trạng tháiÝ nghĩa
SUCCESSMigration hoàn thành không có lỗi
FAILMigration ném ra lỗi
UNKNOWNTrạng thái ban đầu trước khi thực thi

Trong các lần chạy tiếp theo, các quy trình có trạng thái SUCCESS sẽ bị bỏ qua trừ khi options.alwaysRun được đặt thành true.


Áp dụng trong Các Gói

Mỗi gói backend trong BANA sử dụng các helper này. Bảng dưới đây cho thấy mẫu áp dụng trên tất cả các gói:

Góiindex.tsmigrate.tsĐường dẫn Seed
@nx/salebootstrapApplicationbootstrapMigration[]
@nx/identitybootstrapApplicationbootstrapMigration(identity seeds)
@nx/commercebootstrapApplicationbootstrapMigration(commerce seeds)
@nx/inventorybootstrapApplicationbootstrapMigration(inventory seeds)
@nx/financebootstrapApplicationbootstrapMigration(finance seeds)
@nx/paymentbootstrapApplicationbootstrapMigrationpayment-0001-*, payment-0002-*
@nx/signalbootstrapApplicationN/A (stateless)N/A

Tài liệu Liên quan

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