Skip to content

DefaultApplication

Tổng quan

DefaultApplication là lớp ứng dụng nền tảng mà mọi dịch vụ backend trong hệ thống BANA đều kế thừa. Nó kế thừa từ BaseApplication của IGNIS framework và cung cấp thiết lập chuẩn hóa cho:

  • Middleware CORS và giới hạn body
  • Chiến lược xác thực JWT và Basic
  • Endpoint health check
  • Tài liệu Swagger/OpenAPI với Scalar UI
  • Phục vụ tệp tĩnh
  • Đăng ký IdentityNetworkService cho xác thực liên dịch vụ

Nguồn: packages/core/src/default-application.ts

Xem tham chiếu IGNIS Application để biết chi tiết về lớp cha BaseApplication.

Định nghĩa Lớp

typescript
import { BaseApplication, IApplicationInfo } from '@venizia/ignis';

export class DefaultApplication extends BaseApplication {
  protected applicationRoles: string[] = [];

  // Configuration helpers
  getApplicationRoles(): string[];
  override getAppInfo(): IApplicationInfo;

  // Lifecycle hooks
  preConfigure(): void;
  async postConfigure(): Promise<void>;

  // Middleware
  override async setupMiddlewares(): Promise<void>;

  // Registration methods (override in child classes)
  staticConfigure(): void;
  configureDatasources(): void;
  configureRepositories(): void;
  configureServices(): void;
  configureComponents(): void;
  configureSecurity(): void;
  configureControllers(): void;
}

Sơ đồ Kế thừa

Vòng đời và Trình tự Khởi động

Thứ tự Gọi preConfigure()

Phương thức preConfigure() được IGNIS framework gọi trước khi ứng dụng khởi chạy. Nó gọi các phương thức đăng ký theo thứ tự cố định:

typescript
preConfigure() {
  this.applicationRoles = this.getApplicationRoles();

  this.configureDatasources();   // 1. Data sources
  this.configureRepositories();  // 2. Repositories
  this.configureServices();      // 3. Services
  this.configureComponents();    // 4. Components (HealthCheck, Swagger)
  this.configureSecurity();      // 5. Authentication strategies
  this.configureControllers();   // 6. Controllers
}

Trình tự Khởi động Đầy đủ

Cấu hình Middleware

CORS

Middleware CORS được cấu hình với các giá trị mặc định cho phép rộng rãi, phù hợp cho phát triển và triển khai qua API gateway.

typescript
cors: {
  enable: true,
  path: '*',
  origin: '*',
  allowMethods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],
  allowHeaders: [/* see table below */],
  exposeHeaders: [/* see table below */],
  maxAge: 86_400,  // 24 hours
  credentials: true,
}

Các Header Yêu cầu Được phép:

HeaderHằng số IGNIS
AuthorizationHTTP.Headers.AUTHORIZATION
Content-TypeHTTP.Headers.CONTENT_TYPE
X-Request-ChannelHTTP.Headers.REQUEST_CHANNEL
X-Count-DataHTTP.Headers.REQUEST_COUNT_DATA
X-Device-InfoHTTP.Headers.REQUEST_DEVICE_INFO
X-Tracing-IdHTTP.Headers.REQUEST_TRACING_ID
timezoneTùy chỉnh
timezone-offsetTùy chỉnh
x-auth-providerTùy chỉnh
x-forward-forTùy chỉnh
x-localeTùy chỉnh
x-real-ipTùy chỉnh

Các Header Phản hồi Được phơi bày:

HeaderHằng số IGNIS
Content-LengthHTTP.Headers.CONTENT_LENGTH
Content-RangeHTTP.Headers.CONTENT_RANGE
Content-TypeHTTP.Headers.CONTENT_TYPE
X-Count-DataHTTP.Headers.RESPONSE_COUNT_DATA
X-Response-FormatHTTP.Headers.RESPONSE_FORMAT
x-custom-headerTùy chỉnh

Giới hạn Body

typescript
bodyLimit: {
  enable: true,
  path: '*',
  maxSize: 100 * 1024 * 1024,  // 100 MB
  onError: c => c.json({}, 413),  // HTTP 413 Content Too Large
}

Thiết lập Thành phần

Health Check

Được đăng ký tại endpoint /health. Trả về thông tin trạng thái ứng dụng.

typescript
this.bind<IHealthCheckOptions>({
  key: HealthCheckBindingKeys.HEALTH_CHECK_OPTIONS,
}).toValue({
  restOptions: { path: '/health' },
});
this.component(HealthCheckComponent);

Xem tham chiếu IGNIS Health Check để biết định dạng phản hồi và tùy chỉnh.

Swagger / OpenAPI

Cung cấp ba endpoint cho tài liệu API:

Đường dẫnMô tả
/docĐường dẫn cơ sở tài liệu
/openapi.jsonĐặc tả OpenAPI 3.0 (JSON)
/explorerGiao diện tham chiếu API Scalar
typescript
this.bind<ISwaggerOptions>({ key: SwaggerBindingKeys.SWAGGER_OPTIONS }).toValue({
  restOptions: {
    base: { path: '/doc' },
    doc: { path: '/openapi.json' },
    ui: { path: '/explorer', type: 'scalar' },
  },
  explorer: {
    openapi: '3.0.0',
    info: {
      title: 'API Documentation',
      version: this.getAppInfo().version,
      description: 'API documentation for your service',
    },
    servers: [
      {
        url: applicationEnvironment.get<string>(EnvironmentKeys.APP_ENV_APPLICATION_EXPLORER_URL),
        description: 'Application Server URL',
      },
    ],
  },
});
this.component(SwaggerComponent);

Xem tham chiếu IGNIS Swagger để biết đầy đủ tùy chọn.

Thiết lập Bảo mật

Xác thực JWT

Được cấu hình sử dụng ba biến môi trường:

BiếnMô tả
APP_ENV_APPLICATION_SECRETKhóa bí mật cấp ứng dụng
APP_ENV_JWT_SECRETKhóa ký JWT
APP_ENV_JWT_EXPIRES_INThời gian hết hạn token tính bằng giây
typescript
this.bind<IJWTTokenServiceOptions>({
  key: AuthenticateBindingKeys.JWT_OPTIONS,
}).toValue({
  applicationSecret: applicationEnvironment.get<string>(EnvironmentKeys.APP_ENV_APPLICATION_SECRET),
  jwtSecret: applicationEnvironment.get<string>(EnvironmentKeys.APP_ENV_JWT_SECRET),
  getTokenExpiresFn: () => {
    const jwtExpiresIn = applicationEnvironment.get<string>(EnvironmentKeys.APP_ENV_JWT_EXPIRES_IN);
    return parseInt(jwtExpiresIn);
  },
});

Xác thực Basic

Xác thực Basic được ủy quyền cho Identity Service thông qua IdentityNetworkService.signIn(). Khi một controller sử dụng @authenticate(['basic']), thông tin xác thực được chuyển tiếp đến identity service để xác minh.

typescript
this.bind<IBasicTokenServiceOptions>({
  key: AuthenticateBindingKeys.BASIC_OPTIONS,
}).toValue({
  verifyCredentials: async (opts) => {
    const identityNetworkService = this.get<IdentityNetworkService>({
      key: 'services.IdentityNetworkService',
    });

    return identityNetworkService.signIn({
      identifier: { scheme: 'username', value: opts.credentials.username },
      credential: { scheme: 'basic', value: opts.credentials.password },
    });
  },
});

Đăng ký Chiến lược

Cả hai chiến lược được đăng ký với AuthenticationStrategyRegistry của IGNIS:

typescript
this.component(AuthenticateComponent);
AuthenticationStrategyRegistry.getInstance().register({
  container: this,
  strategies: [
    { name: Authentication.STRATEGY_JWT, strategy: JWTAuthenticationStrategy },
    { name: Authentication.STRATEGY_BASIC, strategy: BasicAuthenticationStrategy },
  ],
});

Xem tham chiếu IGNIS Authentication để biết chi tiết chiến lược.

Luồng Xác thực

Phục vụ Tệp Tĩnh

Phương thức staticConfigure() phục vụ các tệp từ thư mục public/ tương đối với gói @nx/core:

typescript
staticConfigure(): void {
  this.static({ folderPath: path.join(__dirname, '../public') });
}

Cách Mở rộng trong Các Gói Con

Mỗi gói tạo lớp Application riêng kế thừa DefaultApplication và ghi đè các phương thức đăng ký:

typescript
// packages/sale/src/application.ts
import { DefaultApplication } from '@nx/core';

export class Application extends DefaultApplication {
  override preConfigure(): void {
    // Call the parent — registers IdentityNetworkService,
    // HealthCheck, Swagger, JWT, Basic auth
    super.preConfigure();

    // Additional package-specific setup happens in overridden methods
  }

  override configureDatasources(): void {
    super.configureDatasources();
    // Register package-specific datasources if needed
  }

  override configureRepositories(): void {
    super.configureRepositories();
    this.repository(SaleOrderRepository);
    this.repository(SaleOrderItemRepository);
  }

  override configureServices(): void {
    super.configureServices();
    this.service(SaleOrderService);
    this.service(CheckoutService);
  }

  override configureComponents(): void {
    super.configureComponents();
    this.component(ApplicationPaymentComponent);
  }

  override configureControllers(): void {
    super.configureControllers();
    this.controller(SaleOrderController);
  }

  override async postConfigure(): Promise<void> {
    await super.postConfigure();
    // Run after all components are bound
  }
}

Luôn gọi super

Khi ghi đè bất kỳ phương thức đăng ký nào, luôn gọi super.<method>() trước để giữ lại các đăng ký mặc định (IdentityNetworkService, HealthCheck, Swagger, JWT/Basic auth).

Biến Môi trường

BiếnBắt buộcMô tả
APP_ENV_APPLICATION_SECRETKhóa bí mật cấp ứng dụng cho JWT
APP_ENV_JWT_SECRETKhóa ký JWT
APP_ENV_JWT_EXPIRES_INThời gian hết hạn token tính bằng giây
APP_ENV_APPLICATION_ROLESKhôngDanh sách định danh vai trò phân cách bằng dấu phẩy
APP_ENV_IDENTITY_SERVICE_BASE_URLURL Identity service cho ủy quyền Basic auth
APP_ENV_APPLICATION_EXPLORER_URLKhôngURL server hiển thị trong Swagger explorer

Tài liệu Liên quan

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