Skip to content

Tiện ích Core

Tổng quan

Package @nx/core cung cấp các lớp tiện ích thiết yếu được dùng trên tất cả service backend. Những tiện ích này xử lý việc sinh ID, mã hoá, thao tác ngày giờ và quản lý request context.

Liên kết nhanh

Tiện íchNguồnMô tả
IdGeneratorsrc/utilities/id-generator.utility.tsSingleton sinh ID Snowflake
CryptoUtilitysrc/utilities/crypto.utility.tsMã hoá AES-256-GCM và ký HMAC
DateUtilitysrc/utilities/date.utility.tsdayjs đã cấu hình sẵn cùng các plugin
RequestContextsrc/utilities/request.utility.tsTrích xuất request context và định dạng phản hồi

Cách các tiện ích ánh xạ vào các tầng của ứng dụng:

Cấu trúc thư mục

packages/core/src/utilities/
├── index.ts                  # Barrel exports
├── id-generator.utility.ts   # Snowflake ID singleton wrapper
├── crypto.utility.ts         # AES-256-GCM encryption + HMAC signing
├── date.utility.ts           # Pre-configured dayjs
└── request.utility.ts        # Request context + response helpers

IdGenerator

Sinh ID phân tán dựa trên Snowflake, cho các định danh duy nhất toàn cục và có thể sắp xếp.

  • Phân tán: An toàn khi triển khai nhiều instance nhờ Worker ID duy nhất (0--1023)
  • Sắp xếp được: ID được sắp theo thứ tự thời gian
  • Gọn nhẹ: Chuỗi mã hoá Base62 (10--12 ký tự)
  • Không cần điều phối: Không cần một máy chủ sinh ID tập trung
typescript
import { IdGenerator } from '@nx/core';

const generator = IdGenerator.getInstance();
const id = generator.nextId();
// "9du1sJXO88"

Tìm hiểu thêm về IdGenerator -->

CryptoUtility

Mật mã ở cấp ứng dụng: mã hoá đối xứng AES-256-GCM dùng APP_ENV_APPLICATION_SECRET, cùng với ký HMAC-SHA256 cho payload của webhook.

  • Singleton: CryptoUtility.getInstance() -- khởi tạo một lần với application secret
  • Mã hoá/Giải mã: Lưu trữ thông tin xác thực, các giá trị cấu hình
  • : Chữ ký cho payload của webhook (timestamp|eventType|parts... nối với nhau bằng dấu pipe)
typescript
import { CryptoUtility } from '@nx/core';

const crypto = CryptoUtility.getInstance();

// Encrypt sensitive data
const encrypted = crypto.encrypt('my-api-key');

// Decrypt it back
const original = crypto.decrypt(encrypted);

// Sign a webhook payload
const signature = crypto.sign({
  timestamp: Date.now(),
  eventType: 'payment.success',
  parts: ['txn_123', '50000'],
  secret: 'webhook-secret',
});

Tìm hiểu thêm về CryptoUtility -->

DateUtility

Instance Day.js đã cấu hình sẵn với hỗ trợ múi giờ và các plugin thông dụng.

  • Hỗ trợ múi giờ: Mặc định Asia/Ho_Chi_Minh (có thể cấu hình qua APP_ENV_APPLICATION_TIMEZONE)
  • Plugin phong phú: customParseFormat, timezone, isoWeek, utc, isSameOrBefore, isSameOrAfter
  • Nhất quán: Cùng một cấu hình trên mọi service
typescript
import { dayjs } from '@nx/core';

// Current time in default timezone
const now = dayjs();

// Parse with custom format
const date = dayjs('20/01/2025', 'DD/MM/YYYY');

// Compare dates
const isInRange =
  dayjs('2025-01-15').isSameOrAfter('2025-01-01') &&
  dayjs('2025-01-15').isSameOrBefore('2025-01-31');

Tìm hiểu thêm về DateUtility -->

RequestContext

Bộ truy cập request context có kiểu để lấy thông tin người dùng hiện tại, thông tin phân quyền, và các helper định dạng phản hồi.

  • An toàn kiểu: Hỗ trợ TypeScript đầy đủ cho JWT payload
  • Tích hợp JWT: Trích xuất người dùng, role và permission từ JWT
  • Kiểm tra role: Lối tắt isAlwaysAllowed cho SUPER_ADMIN và ADMIN
  • Định dạng phản hồi: formatResponse, formatArrayResponse, normalizeCountableData
typescript
import { useRequestContext } from '@nx/core';

async myMethod() {
  const { currentUser, userId, roles, isAlwaysAllowed, formatResponse } = useRequestContext();

  if (!isAlwaysAllowed && !roles.includes('editor')) {
    throw new ForbiddenError();
  }

  const result = await this.repository.create({
    data: { createdBy: userId },
  });

  return formatResponse({ data: result, count: 1 });
}

Tìm hiểu thêm về RequestContext -->

Import

Tất cả tiện ích đều được re-export từ điểm vào chính của package.

typescript
// Import from main package
import { IdGenerator, CryptoUtility, dayjs, useRequestContext } from '@nx/core';

// Or import from utilities sub-path
import { IdGenerator, CryptoUtility, dayjs, useRequestContext } from '@nx/core/utilities';

Tài liệu liên quan

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