Skip to content

Core Utilities

Overview

The @nx/core package provides essential utility classes used across all backend services. These utilities handle ID generation, encryption, date manipulation, and request context management.

UtilitySourceDescription
IdGeneratorsrc/utilities/id-generator.utility.tsSnowflake ID singleton
CryptoUtilitysrc/utilities/crypto.utility.tsAES-256-GCM encryption and HMAC signing
DateUtilitysrc/utilities/date.utility.tsPre-configured dayjs with plugins
RequestContextsrc/utilities/request.utility.tsRequest context extraction and response formatting

How utilities map to application layers:

Directory Structure

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

Snowflake-based distributed ID generation for globally unique, sortable identifiers.

  • Distributed: Safe for multi-instance deployments via unique Worker IDs (0--1023)
  • Sortable: IDs are time-ordered
  • Compact: Base62-encoded string (10--12 characters)
  • No Coordination: No central ID server required
typescript
import { IdGenerator } from '@nx/core';

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

Learn more about IdGenerator -->

CryptoUtility

Application-level cryptography: AES-256-GCM symmetric encryption using APP_ENV_APPLICATION_SECRET, plus HMAC-SHA256 payload signing for webhooks.

  • Singleton: CryptoUtility.getInstance() -- initialized once with the application secret
  • Encrypt/Decrypt: Credential storage, configuration values
  • Sign: Webhook payload signatures (timestamp|eventType|parts... joined with 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',
});

Learn more about CryptoUtility -->

DateUtility

Pre-configured Day.js instance with timezone support and common plugins.

  • Timezone Support: Default Asia/Ho_Chi_Minh (configurable via APP_ENV_APPLICATION_TIMEZONE)
  • Rich Plugins: customParseFormat, timezone, isoWeek, utc, isSameOrBefore, isSameOrAfter
  • Consistent: Same configuration across all services
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');

Learn more about DateUtility -->

RequestContext

Typed request context accessor for retrieving current user, authorization info, and response formatting helpers.

  • Type-Safe: Full TypeScript support for JWT payload
  • JWT Integration: Extract user, roles, and permissions from JWT
  • Role Checking: isAlwaysAllowed shortcut for SUPER_ADMIN and ADMIN
  • Response Formatting: 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 });
}

Learn more about RequestContext -->

Import

All utilities are re-exported from the main package entry point.

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

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