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ý
IdentityNetworkServicecho 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
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:
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.
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:
| Header | Hằng số IGNIS |
|---|---|
Authorization | HTTP.Headers.AUTHORIZATION |
Content-Type | HTTP.Headers.CONTENT_TYPE |
X-Request-Channel | HTTP.Headers.REQUEST_CHANNEL |
X-Count-Data | HTTP.Headers.REQUEST_COUNT_DATA |
X-Device-Info | HTTP.Headers.REQUEST_DEVICE_INFO |
X-Tracing-Id | HTTP.Headers.REQUEST_TRACING_ID |
timezone | Tùy chỉnh |
timezone-offset | Tùy chỉnh |
x-auth-provider | Tùy chỉnh |
x-forward-for | Tùy chỉnh |
x-locale | Tùy chỉnh |
x-real-ip | Tùy chỉnh |
Các Header Phản hồi Được phơi bày:
| Header | Hằng số IGNIS |
|---|---|
Content-Length | HTTP.Headers.CONTENT_LENGTH |
Content-Range | HTTP.Headers.CONTENT_RANGE |
Content-Type | HTTP.Headers.CONTENT_TYPE |
X-Count-Data | HTTP.Headers.RESPONSE_COUNT_DATA |
X-Response-Format | HTTP.Headers.RESPONSE_FORMAT |
x-custom-header | Tùy chỉnh |
Giới hạn Body
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.
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ẫn | Mô tả |
|---|---|
/doc | Đường dẫn cơ sở tài liệu |
/openapi.json | Đặc tả OpenAPI 3.0 (JSON) |
/explorer | Giao diện tham chiếu API Scalar |
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ến | Mô tả |
|---|---|
APP_ENV_APPLICATION_SECRET | Khóa bí mật cấp ứng dụng |
APP_ENV_JWT_SECRET | Khóa ký JWT |
APP_ENV_JWT_EXPIRES_IN | Thời gian hết hạn token tính bằng giây |
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.
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:
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:
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ý:
// 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ến | Bắt buộc | Mô tả |
|---|---|---|
APP_ENV_APPLICATION_SECRET | Có | Khóa bí mật cấp ứng dụng cho JWT |
APP_ENV_JWT_SECRET | Có | Khóa ký JWT |
APP_ENV_JWT_EXPIRES_IN | Có | Thời gian hết hạn token tính bằng giây |
APP_ENV_APPLICATION_ROLES | Không | Danh sách định danh vai trò phân cách bằng dấu phẩy |
APP_ENV_IDENTITY_SERVICE_BASE_URL | Có | URL Identity service cho ủy quyền Basic auth |
APP_ENV_APPLICATION_EXPLORER_URL | Không | URL server hiển thị trong Swagger explorer |