Skip to content

Tien ich Core

Tong quan

Goi @nx/core cung cap cac lop tien ich thiet yeu duoc su dung tren tat ca cac dich vu backend. Cac tien ich nay xu ly viec tao ID, ma hoa, thao tac ngay thang, va quan ly ngu canh yeu cau.

Lien ket Nhanh

Tien ichNguonMo ta
IdGeneratorsrc/utilities/id-generator.utility.tsSingleton ID Snowflake
CryptoUtilitysrc/utilities/crypto.utility.tsMa hoa AES-256-GCM va ky HMAC
DateUtilitysrc/utilities/date.utility.tsdayjs duoc cau hinh san voi cac plugin
RequestContextsrc/utilities/request.utility.tsTrich xuat ngu canh yeu cau va dinh dang phan hoi

Cach cac tien ich anh xa vao cac lop ung dung:

Cau truc Thu muc

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

Tao ID phan tan dua tren Snowflake cho cac dinh danh duy nhat toan cau, co the sap xep.

  • Phan tan: An toan cho trien khai nhieu instance thong qua Worker ID duy nhat (0--1023)
  • Co the sap xep: ID duoc sap xep theo thoi gian
  • Nho gon: Chuoi ma hoa Base62 (10--12 ky tu)
  • Khong Can Phoi hop: Khong can may chu ID trung tam
typescript
import { IdGenerator } from '@nx/core';

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

Tim hieu them ve IdGenerator -->

CryptoUtility

Mat ma hoc cap ung dung: ma hoa doi xung AES-256-GCM su dung APP_ENV_APPLICATION_SECRET, cong voi ky HMAC-SHA256 cho webhook.

  • Singleton: CryptoUtility.getInstance() -- khoi tao mot lan voi application secret
  • Ma hoa/Giai ma: Luu tru thong tin xac thuc, gia tri cau hinh
  • Ky: Chu ky payload webhook (timestamp|eventType|parts... noi bang 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',
});

Tim hieu them ve CryptoUtility -->

DateUtility

Instance Day.js duoc cau hinh san voi ho tro mui gio va cac plugin pho bien.

  • Ho tro Mui gio: Mac dinh Asia/Ho_Chi_Minh (cau hinh qua APP_ENV_APPLICATION_TIMEZONE)
  • Plugin Phong phu: customParseFormat, timezone, isoWeek, utc, isSameOrBefore, isSameOrAfter
  • Nhat quan: Cung cau hinh tren tat ca dich vu
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');

Tim hieu them ve DateUtility -->

RequestContext

Trinh truy cap ngu canh yeu cau co kieu de lay thong tin nguoi dung hien tai, thong tin uy quyen, va cac helper dinh dang phan hoi.

  • An toan Kieu: Ho tro TypeScript day du cho JWT payload
  • Tich hop JWT: Trich xuat nguoi dung, vai tro, va quyen tu JWT
  • Kiem tra Vai tro: Loi tat isAlwaysAllowed cho SUPER_ADMIN va ADMIN
  • Dinh dang Phan hoi: 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 });
}

Tim hieu them ve RequestContext -->

Import

Tat ca tien ich deu duoc re-export tu diem truy cap chinh cua goi.

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';

Tai lieu Lien quan

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