@hichchi/nest-core
v0.0.9
Published
Comprehensive NestJS core library providing application bootstrap, caching, decorators, filters, interceptors, logging, middleware, services, validators, and essential utilities for enterprise-grade applications
Downloads
969
Readme
🚀 @hichchi/nest-core
Description
Comprehensive NestJS core library providing application bootstrap, caching, decorators, filters, interceptors, logging, middleware, services, validators, and essential utilities for enterprise-grade applications
Part of the Hichchi ecosystem - A powerful, scalable application built with Nx workspace
📋 Table of Contents
- 📦 Installation
- ⚡ Quick Start
- 📋 Prerequisites
- 🌟 Overview
- ✨ Features
- 🚀 Usage
- 🔧 Configuration Reference
- 🔧 Development
- 📖 API Documentation
📦 Installation
npm install @hichchi/nest-core⚡ Quick Start
Get up and running with essential NestJS utilities in just a few minutes:
// 1. Install the package
npm install @hichchi/nest-core
// 2. Import utilities in your NestJS application
import { hichchiBootstrap, AxiosHttpService } from '@hichchi/nest-core';
// 3. Bootstrap your application with enhanced features
async function bootstrap() {
await hichchiBootstrap(AppModule, {
port: 3000,
});
}
bootstrap();📋 Prerequisites
Before installing @hichchi/nest-core, ensure you have:
Required Dependencies
- Node.js: ^20.0.0
- NestJS: ^11.0.0
- TypeScript: ~5.9.3
Peer Dependencies
# For core functionality
npm install @nestjs/common @nestjs/core
npm install rxjs reflect-metadata
# For caching features
npm install @nestjs/cache-manager cache-manager @keyv/redisInternal Dependencies
This package depends on:
npm install @hichchi/nest-connector @hichchi/utilsOptional Dependencies
For enhanced features:
# For HTTP client functionality
npm install axios
# For advanced validation
npm install class-validator class-transformerSystem Requirements
- Compatible with all major operating systems
- Supports both CommonJS and ES modules
- TypeScript definitions included
🌟 Overview
🎯 Your essential toolkit for NestJS applications. From application bootstrapping to HTTP services, from validation utilities to custom decorators - everything you need to build robust, scalable NestJS applications with enterprise-grade components and utilities.
✨ Features
🚀 Application Bootstrap
- 🏗️ Enhanced Bootstrap - Advanced application initialization with
hichchiBootstrap - 🔧 Configuration Management - Streamlined app configuration and setup
- 🔧 Environment Setup - Automated environment-specific configurations
- 📊 Health Checks - Built-in application health monitoring
🌐 HTTP Services
- 🔗 Axios HTTP Service - Pre-configured HTTP client with advanced features
- 🔄 Request/Response Interceptors - Built-in request and response handling
- ⚡ Retry Logic - Automatic retry mechanisms for failed requests
- 📈 Request Logging - Comprehensive HTTP request/response logging
🎯 Helpful Decorators
- 📝 @Dto - Enhanced DTO validation and transformation decorators
- 🔄 @UseTransformInterceptor - Apply transformation interceptors to endpoints
- 🎫 Custom Metadata - Advanced metadata handling decorators
- 🏷️ Parameter Decorators - Specialized parameter extraction decorators
🛠️ Utility Functions
- 🔍 Exception Utils - Advanced exception handling and formatting utilities
- ✅ Validation Utils - Comprehensive validation helper functions
- 🌍 Global Utils - Application-wide utility functions
- 🔧 General Utils - Common utility functions for everyday tasks
🔐 Validators
- 🎲 Random Hex Validator - Validate random hexadecimal strings
- 🎫 Token Verification - Advanced token validation and verification
- 📋 Custom Validators - Extensible validation framework
- ⚡ Performance Optimized - Fast validation with minimal overhead
🏗️ Core Components
- 🗄️ Cache Management - Advanced caching strategies and utilities
- 🔄 Data Converters - Type-safe data transformation utilities
- 🚨 Exception Handling - Comprehensive error handling framework
- 🔍 Filters & Interceptors - Pre-built filters and interceptors
- 📊 Logging System - Advanced logging with multiple transports
- 🔗 Middleware Collection - Essential middleware components
🔧 Configuration Options
- 🔧 Flexible Setup - Easy integration with existing NestJS applications
- 🎛️ Customizable Components - Configure utilities to match your needs
- 🔌 Modular Architecture - Use only the components you need
- 📦 Zero Configuration - Works out of the box with sensible defaults
🚀 Usage
Using Bootstrap Functionality
hichchiBootstrap
This function provides enhanced application bootstrapping with built-in configuration for CORS, validation, global filters, interceptors, and logging. It simplifies the setup process by providing sensible defaults while allowing customization.
import { hichchiBootstrap } from "@hichchi/nest-core";
import { AppModule } from "./app.module";
// Basic usage with default configuration
async function bootstrap() {
await hichchiBootstrap(AppModule);
}
// Advanced usage with custom configuration
async function bootstrap() {
await hichchiBootstrap(AppModule, {
port: 3000,
globalPrefix: "api/v1",
allowedOrigins: ["http://localhost:3000", "https://myapp.com"],
validation: {
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: {
enableImplicitConversion: true,
},
},
globalFilters: true, // Enable global exception filters
globalInterceptors: true, // Enable global interceptors
logger: true, // Enable enhanced logging
});
}
bootstrap();Using HTTP Services
AxiosHttpService
This service provides a wrapper around Axios with enhanced error handling, automatic retries, and NestJS integration. It converts Axios responses to promises and handles HTTP exceptions appropriately.
import { Injectable } from "@nestjs/common";
import { AxiosHttpService } from "@hichchi/nest-core";
import { AxiosRequestConfig } from "axios";
@Injectable()
export class ApiService {
constructor(private readonly httpService: AxiosHttpService) {}
// GET request with configuration
async getUsers(page: number = 1, limit: number = 10) {
const config: AxiosRequestConfig = {
params: { page, limit },
timeout: 5000,
headers: {
"Content-Type": "application/json",
},
};
try {
const response = await this.httpService.get("/users", config);
return response.data;
} catch (error) {
// Error is automatically converted to appropriate NestJS exception
throw error;
}
}
// POST request with data
async createUser(userData: any) {
const config: AxiosRequestConfig = {
timeout: 10000,
headers: {
Authorization: `Bearer ${this.getAuthToken()}`,
"Content-Type": "application/json",
},
};
return this.httpService.post("/users", userData, config);
}
// PUT request for updates
async updateUser(id: string, userData: any) {
const config: AxiosRequestConfig = {
timeout: 10000,
headers: {
Authorization: `Bearer ${this.getAuthToken()}`,
},
};
return this.httpService.put(`/users/${id}`, userData, config);
}
// PATCH request for partial updates
async patchUser(id: string, partialData: any) {
return this.httpService.patch(`/users/${id}`, partialData, {
headers: {
Authorization: `Bearer ${this.getAuthToken()}`,
},
});
}
// DELETE request
async deleteUser(id: string) {
const config: AxiosRequestConfig = {
headers: {
Authorization: `Bearer ${this.getAuthToken()}`,
},
};
return this.httpService.delete(`/users/${id}`, config);
}
private getAuthToken(): string {
// Implementation to get auth token
return "your-auth-token";
}
}Using Middlewares
Body Parser Middlewares
The library provides specialized body parser middlewares for different content types.
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
import {
JsonBodyParserMiddleware,
RawBodyParserMiddleware,
} from "@hichchi/nest-core";
@Module({})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
// Apply JSON body parser to specific routes
consumer.apply(JsonBodyParserMiddleware).forRoutes("api/webhooks/json");
// Apply raw body parser for webhook endpoints
consumer.apply(RawBodyParserMiddleware).forRoutes("api/webhooks/raw");
}
}
// Use in webhook controllers
@Controller("api/webhooks")
export class WebhookController {
@Post("json")
handleJsonWebhook(@Body() body: any) {
// Body is automatically parsed as JSON
return this.processJsonWebhook(body);
}
@Post("raw")
handleRawWebhook(@Req() req: Request) {
// Access raw body from request
const rawBody = req.body;
return this.processRawWebhook(rawBody);
}
}Using Logger Service
LoggerService
This service provides comprehensive logging functionality with multiple log levels, custom formatting, and transport options.
import { Injectable } from "@nestjs/common";
import { LoggerService } from "@hichchi/nest-core";
@Injectable()
export class UserService {
constructor(private readonly logger: LoggerService) {
// Set context for this service
this.logger = new LoggerService("UserService");
}
async createUser(userData: any) {
this.logger.log("Creating new user", { userData });
try {
const user = await this.userRepository.save(userData);
this.logger.info("User created successfully", { userId: user.id });
return user;
} catch (error) {
this.logger.error("Failed to create user", error, { userData });
throw error;
}
}
async findUser(id: string) {
this.logger.debug("Finding user by ID", { id });
const user = await this.userRepository.findById(id);
if (!user) {
this.logger.warn("User not found", { id });
return null;
}
this.logger.verbose("User found", { userId: user.id });
return user;
}
async deleteUser(id: string) {
this.logger.log("Deleting user", { id });
try {
await this.userRepository.delete(id);
this.logger.info("User deleted successfully", { id });
} catch (error) {
this.logger.fatal("Critical error during user deletion", error, { id });
throw error;
}
}
}Logger Configuration
Configure the logger with custom options and transports.
import { LoggerService } from "@hichchi/nest-core";
// Configure logger globally
LoggerService.configure({
level: "info",
format: "json",
transports: [
{
type: "console",
options: {
colorize: true,
timestamp: true,
},
},
{
type: "file",
options: {
filename: "logs/app.log",
maxsize: 5242880, // 5MB
maxFiles: 5,
},
},
],
});
// Use in different contexts
const authLogger = new LoggerService("AuthService");
const dbLogger = new LoggerService("DatabaseService");
// Different log levels
authLogger.verbose("Detailed debug information");
authLogger.debug("Debug information");
authLogger.info("General information");
authLogger.log("Standard log message");
authLogger.warn("Warning message");
authLogger.error("Error occurred", new Error("Sample error"));
authLogger.fatal("Critical system error", new Error("Fatal error"));Using Utilities
Exception Utilities
Utility functions for handling and transforming exceptions.
import {
isHttpException,
transformException,
getExceptionMessage,
} from "@hichchi/nest-core";
@Injectable()
export class ErrorHandlerService {
handleError(error: any) {
// Check if error is an HTTP exception
if (isHttpException(error)) {
console.log("HTTP Exception:", error.getStatus(), error.message);
return;
}
// Transform generic error to HTTP exception
const httpException = transformException(error);
console.log("Transformed exception:", httpException);
// Extract meaningful error message
const message = getExceptionMessage(error);
console.log("Error message:", message);
}
async processWithErrorHandling(operation: () => Promise<any>) {
try {
return await operation();
} catch (error) {
this.handleError(error);
throw error;
}
}
}Validation Utilities
Utility functions for validation and data transformation.
import {
validateObject,
transformData,
sanitizeInput,
} from "@hichchi/nest-core";
@Injectable()
export class ValidationService {
async validateUserInput(userData: any) {
// Validate object structure
const isValid = await validateObject(userData, {
email: "required|email",
name: "required|string|min:2",
age: "optional|number|min:18",
});
if (!isValid) {
throw new BadRequestException("Invalid user data");
}
// Transform data
const transformedData = transformData(userData, {
email: "lowercase|trim",
name: "trim|capitalize",
});
// Sanitize input
const sanitizedData = sanitizeInput(transformedData);
return sanitizedData;
}
}Global Utilities
General utility functions for common operations.
import { getGlobal, setGlobal, isOriginAllowed } from "@hichchi/nest-core";
// Global state management
setGlobal("appConfig", {
version: "1.0.0",
environment: "production",
});
const config = getGlobal("appConfig");
console.log("App version:", config.version);
// Origin validation for CORS
const allowedOrigins = ["http://localhost:3000", "https://myapp.com"];
@Injectable()
export class CorsService {
validateOrigin(origin: string): boolean {
return isOriginAllowed(origin, allowedOrigins);
}
getCorsOptions() {
return {
origin: (origin: string, callback: Function) => {
if (this.validateOrigin(origin)) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
};
}
}🔧 Configuration Reference
Bootstrap Configuration
interface AppConfiguration {
/** Port number on which the application will listen (default: 3000) */
port?: number;
/** Global prefix for all routes in the application */
globalPrefix?: string;
/** List of allowed origins for CORS */
allowedOrigins?: string[];
/** Validation pipe configuration */
validation?: boolean | ValidationPipeOptions;
/** Global exception filters configuration */
globalFilters?: boolean | ExceptionFilter[];
/** Global interceptors configuration */
globalInterceptors?: boolean | NestInterceptor[];
/** Logger configuration */
logger?: boolean | LoggerService;
}
// Bootstrap your application with enhanced features
await hichchiBootstrap(AppModule, {
port: 3000,
globalPrefix: "api",
allowedOrigins: ["localhost:3000", "example.com"],
validation: {
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
},
globalFilters: true,
globalInterceptors: true,
logger: true,
});HTTP Service Configuration
import { AxiosHttpService } from "@hichchi/nest-core";
import { AxiosRequestConfig } from "axios";
@Injectable()
export class MyService {
constructor(private readonly httpService: AxiosHttpService) {}
async getData() {
const config: AxiosRequestConfig = {
timeout: 5000,
headers: { Authorization: "Bearer token" },
params: { page: 1, limit: 10 },
};
return this.httpService.get<DataResponse>("/api/data", config);
}
}Logger Configuration
import { LoggerService, LoggerOptions } from "@hichchi/nest-core";
import { LogLevel } from "@hichchi/nest-core";
// Configure logger globally
const loggerOptions: LoggerOptions = {
appName: "MyApp",
level: LogLevel.INFO,
logsDir: "./logs",
colors: true,
prettyPrint: true,
showAppName: true,
timestampFormat: "YYYY-MM-DD hh:mm:ss A",
};
LoggerService.configure(loggerOptions);
// Create logger instance with context
const logger = new LoggerService("MyService");
logger.log("Service initialized");🔧 Development
Building
nx build nest-coreCompile and bundle the core utilities for production use.
Testing
nx test nest-coreRun comprehensive unit tests powered by Jest.
Made with ❤️ by Hichchi Dev
Accelerating NestJS development with essential bootstrap, caching, logging, middleware, and enterprise-grade utilities
📖 API Documentation
Complete technical reference for all classes, interfaces, methods, and types in this library.
Auto-generated by TypeDoc - Browse through detailed API references, code examples, and implementation guides below.
📋 API Table of Contents
- Classes
- Functions
- BooleanTransformer()
- BooleanTransformerWithDefault()
- colorize()
- consoleFormat()
- DateTransformer()
- Dto()
- errorFileFormat()
- FileFormFieldTransformer()
- FileOrTextFormFieldTransformer()
- findFirstConstraint()
- formatMessage()
- generateValidationErrorResponse()
- getGlobal()
- hichchiBootstrap()
- hichchiMetadata()
- httpExceptionFilter()
- isJson()
- isOriginAllowed()
- isRandomHexToken()
- IsRandomHexToken()
- IsVerifyToken()
- MultiValueFormFieldTransformer()
- throwValidationErrors()
- toErrorObject()
- toErrString()
- toJSON()
- toString()
- UseTransformInterceptor()
- validateDto()
- validationPipeExceptionFactory()
- Interfaces
- Type Aliases
- Variables
Classes
AllExceptionsFilter
Defined in: libs/nest-core/src/filters/http-exception.filter.ts:43
Global exception filter that standardizes error responses
This filter catches all unhandled exceptions in the application and transforms them into standardized error responses. It extends NestJS's BaseExceptionFilter and uses the httpExceptionFilter utility to process exceptions before passing them to the parent filter.
The filter ensures that all error responses follow a consistent format with:
- Appropriate HTTP status codes
- Standardized error codes
- Clear error messages
- Optional detailed descriptions
When registered as a global filter, it will catch exceptions from all routes and controllers in the application, providing a centralized error handling mechanism.
Example
// Register as a global filter in your bootstrap function
async function bootstrap(): Promise<void> {
const app = await NestFactory.create(AppModule);
const { httpAdapter } = app.get(HttpAdapterHost);
app.useGlobalFilters(new AllExceptionsFilter(httpAdapter));
await app.listen(3000);
}
bootstrap();See
- httpExceptionFilter The utility function that processes exceptions
- ErrorResponse The standardized error response structure
Extends
BaseExceptionFilter
Constructors
Constructor
new AllExceptionsFilter(applicationRef?): AllExceptionsFilter;Defined in: node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:8
Parameters
applicationRef?
HttpServer<any, any, any>
Returns
Inherited from
BaseExceptionFilter.constructor;Methods
catch()
catch(exception, host): void;Defined in: libs/nest-core/src/filters/http-exception.filter.ts:64
Catches and processes exceptions
This method overrides the catch method from BaseExceptionFilter to process exceptions using the httpExceptionFilter utility before passing them to the parent class's catch method. It extracts the HTTP request from the host and enables logging of unknown exceptions.
The method performs the following steps:
- Extracts the HTTP request from the ArgumentsHost
- Passes the exception, request, and true (to enable logging) to httpExceptionFilter
- Passes the processed exception to the parent class's catch method
Parameters
exception
unknown
The exception object thrown in the application
host
ArgumentsHost
The arguments host object containing the execution context
Returns
void
See
- httpExceptionFilter The utility function that processes exceptions
- BaseExceptionFilter.catch The parent class's catch method
Overrides
BaseExceptionFilter.catch;handleUnknownError()
handleUnknownError(
exception,
host,
applicationRef): void;Defined in: node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:10
Parameters
exception
any
host
ArgumentsHost
applicationRef
| HttpServer<any, any, any> | AbstractHttpAdapter<any, any, any>
Returns
void
Inherited from
BaseExceptionFilter.handleUnknownError;isExceptionObject()
isExceptionObject(err): err is Error;Defined in: node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:11
Parameters
err
any
Returns
err is Error
Inherited from
BaseExceptionFilter.isExceptionObject;isHttpError()
isHttpError(err): err is { message: string; statusCode: number };Defined in: node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:16
Checks if the thrown error comes from the "http-errors" library.
Parameters
err
any
error object
Returns
err is { message: string; statusCode: number }
Inherited from
BaseExceptionFilter.isHttpError;Properties
applicationRef?
readonly
HttpServer<any, any, any>
BaseExceptionFilter.applicationRef;node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:5
httpAdapterHost?
readonly
HttpAdapterHost<AbstractHttpAdapter<any, any, any>>
BaseExceptionFilter.httpAdapterHost;node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:7
AxiosHttpService
Defined in: libs/nest-core/src/services/axios-http.service.ts:49
HTTP client service that wraps NestJS HttpService with improved error handling
This service provides a convenient wrapper around the NestJS HttpService (which is based on Axios) to make HTTP requests with automatic error handling. It converts Axios errors into appropriate NestJS exceptions based on the HTTP status code of the response.
The service offers methods for all standard HTTP methods (GET, POST, PUT, PATCH, DELETE) with full TypeScript support for request and response types.
Example
// Inject the service
constructor(private readonly httpService: AxiosHttpService) {}
// Make a GET request
async getUser(id: string): Promise<User> {
return this.httpService.get<User>(`https://api.example.com/users/${id}`);
}
// Make a POST request with typed request and response
async createUser(userData: CreateUserDto): Promise<User> {
return this.httpService.post<User, CreateUserDto>(
'https://api.example.com/users',
userData
);
}See
HttpService The underlying NestJS HttpService that this service wraps
Constructors
Constructor
new AxiosHttpService(httpService): AxiosHttpService;Defined in: libs/nest-core/src/services/axios-http.service.ts:50
Parameters
httpService
HttpService
Returns
Methods
delete()
delete<T>(url, config?): Promise<T>;Defined in: libs/nest-core/src/services/axios-http.service.ts:322
Performs an HTTP DELETE request
This method sends a DELETE request to the specified URL and returns the response data. DELETE is used to remove resources from the server. It handles the conversion of the Observable returned by HttpService into a Promise, and provides error handling by converting Axios errors into appropriate NestJS exceptions.
Type Parameters
T
The expected type of the response data
Parameters
url
string
The URL to send the request to
config?
AxiosRequestConfig<any>
Optional Axios request configuration
Returns
Promise<T>
A promise that resolves to the response data
Throws
For 400 status responses
Throws
For 401 status responses
Throws
For 403 status responses
Throws
For all other error responses
Example
// Delete a user
const result = await httpService.delete<{ success: boolean }>(
"https://api.example.com/users/123",
);
if (result.success) {
console.log("User deleted successfully");
}
// Delete with authentication and additional parameters
const deleteResult = await httpService.delete<ApiResponse>(
"https://api.example.com/resources/456",
{
headers: { Authorization: "Bearer " + token },
params: { permanent: true },
},
);get()
get<T>(url, config?): Promise<T>;Defined in: libs/nest-core/src/services/axios-http.service.ts:80
Performs an HTTP GET request
This method sends a GET request to the specified URL and returns the response data. It handles the conversion of the Observable returned by HttpService into a Promise, and provides error handling by converting Axios errors into appropriate NestJS exceptions.
Type Parameters
T
The expected type of the response data
Parameters
url
string
The URL to send the request to
config?
AxiosRequestConfig<any>
Optional Axios request configuration
Returns
Promise<T>
A promise that resolves to the response data
Throws
For 400 status responses
Throws
For 401 status responses
Throws
For 403 status responses
Throws
For all other error responses
Example
// Get a user by ID
const user = await httpService.get<User>("https://api.example.com/users/123");
// Get users with query parameters and headers
const users = await httpService.get<User[]>("https://api.example.com/users", {
params: { role: "admin", active: true },
headers: { "X-API-Key": "your-api-key" },
});patch()
patch<T, D>(
url,
data?,
config?): Promise<T>;Defined in: libs/nest-core/src/services/axios-http.service.ts:266
Performs an HTTP PATCH request
This method sends a PATCH request with the provided data to the specified URL and returns the response data. Unlike PUT which replaces an entire resource, PATCH is used for partial updates to a resource. It handles the conversion of the Observable returned by HttpService into a Promise, and provides error handling by converting Axios errors into appropriate NestJS exceptions.
Type Parameters
T
‐
The expected type of the response data
D
any
The type of the request data (defaults to any)
Parameters
url
string
The URL to send the request to
data?
D
Optional data to send in the request body
config?
AxiosRequestConfig<any>
Optional Axios request configuration
Returns
Promise<T>
A promise that resolves to the response data
Throws
For 400 status responses
Throws
For 401 status responses
Throws
For 403 status responses
Throws
For all other error responses
Example
// Partially update a user
interface PatchUserDto {
name?: string;
email?: string;
}
const updatedUser = await httpService.patch<User, PatchUserDto>(
"https://api.example.com/users/123",
{ name: "John Updated" }, // Only update the name
);
// Patch with query parameters
const result = await httpService.patch<ApiResponse, object>(
"https://api.example.com/resources/456",
{ status: "inactive" },
{
params: { version: "2" },
headers: { "X-Reason": "Maintenance" },
},
);post()
post<T, D>(
url,
data?,
config?): Promise<T>;Defined in: libs/nest-core/src/services/axios-http.service.ts:138
Performs an HTTP POST request
This method sends a POST request with the provided data to the specified URL and returns the response data. It handles the conversion of the Observable returned by HttpService into a Promise, and provides error handling by converting Axios errors into appropriate NestJS exceptions.
Type Parameters
T
‐
The expected type of the response data
D
any
The type of the request data (defaults to any)
Parameters
url
string
The URL to send the request to
data?
D
Optional data to send in the request body
config?
AxiosRequestConfig<any>
Optional Axios request configuration
Returns
Promise<T>
A promise that resolves to the response data
Throws
For 400 status responses
Throws
For 401 status responses
Throws
For 403 status responses
Throws
For all other error responses
Example
// Create a new user
interface CreateUserDto {
name: string;
email: string;
}
const newUser = await httpService.post<User, CreateUserDto>(
"https://api.example.com/users",
{ name: "John Doe", email: "[email protected]" },
);
// Post with additional headers
const response = await httpService.post<ApiResponse, FormData>(
"https://api.example.com/upload",
formData,
{ headers: { "Content-Type": "multipart/form-data" } },
);put()
put<T, D>(
url,
data?,
config?): Promise<T>;Defined in: libs/nest-core/src/services/axios-http.service.ts:204
Performs an HTTP PUT request
This method sends a PUT request with the provided data to the specified URL and returns the response data. PUT is typically used for updating existing resources with a complete replacement of the resource. It handles the conversion of the Observable returned by HttpService into a Promise, and provides error handling by converting Axios errors into appropriate NestJS exceptions.
Type Parameters
T
‐
The expected type of the response data
D
any
The type of the request data (defaults to any)
Parameters
url
string
The URL to send the request to
data?
D
Optional data to send in the request body
config?
AxiosRequestConfig<any>
Optional Axios request configuration
Returns
Promise<T>
A promise that resolves to the response data
Throws
For 400 status responses
Throws
For 401 status responses
Throws
For 403 status responses
Throws
For all other error responses
Example
// Update a user (complete replacement)
interface UpdateUserDto {
id: string;
name: string;
email: string;
role: string;
}
const updatedUser = await httpService.put<User, UpdateUserDto>(
"https://api.example.com/users/123",
{
id: "123",
name: "John Doe",
email: "[email protected]",
role: "admin",
},
);
// Put with authentication header
const result = await httpService.put<ApiResponse, object>(
"https://api.example.com/resources/456",
{ status: "active" },
{ headers: { Authorization: "Bearer " + token } },
);CacheModule
Defined in: libs/nest-core/src/cache/cache.module.ts:53
Global cache module that provides Redis-based caching with in-memory fallback
This module integrates NestJS's cache manager with Redis and provides a two-layer caching strategy: an in-memory LRU cache for frequently accessed items and a Redis cache for distributed caching across multiple instances.
The module is marked as @Global(), so it only needs to be imported once in your application's root module.
Examples
// In your app module
@Module({
imports: [
CacheModule.register({
host: "localhost",
port: 6379,
ttl: 3600,
prefix: "myapp:",
}),
],
})
export class AppModule {}// Using with a Redis URL
@Module({
imports: [
CacheModule.register({
url: "redis://username:[email protected]:6379",
ttl: 86400, // 1 day
lruSize: 1000,
}),
],
})
export class AppModule {}Constructors
Constructor
new CacheModule(): CacheModule;Returns
Methods
register()
static register(options): DynamicModule;Defined in: libs/nest-core/src/cache/cache.module.ts:89
Register the cache module with Redis configuration
This static method configures the cache module with the provided Redis options. It sets up a two-layer caching strategy:
- An in-memory LRU cache for frequently accessed items
- A Redis cache for distributed caching across multiple instances
The method validates the provided options and throws a RedisConfigException if neither host nor url is provided.
Parameters
options
Redis connection and caching options
Returns
DynamicModule
A NestJS dynamic module configured for caching
Throws
If neither host nor url is provided in options
Examples
// Register with host-based configuration
CacheModule.register({
host: "localhost",
port: 6379,
ttl: 3600,
});// Register with URL-based configuration
CacheModule.register({
url: "redis://redis.example.com:6379",
prefix: "api:",
lruSize: 500,
});CacheService
Defined in: libs/nest-core/src/cache/services/cache.service.ts:30
Cache Service
This service provides a wrapper around the NestJS cache manager for storing and retrieving data. It offers type-safe methods for getting, setting, and deleting cache entries with error handling.
Example
// Inject the service
constructor(private readonly cacheService: CacheService) {}
// Store a value in cache
await cacheService.set('user:123', { name: 'John Doe' }, 3600); // expires in 1 hour
// Retrieve a value from cache
const user = await cacheService.get<{ name: string }>('user:123');
// Delete a value from cache
await cacheService.delete('user:123');See
CacheModule The module that provides this service
Constructors
Constructor
new CacheService(cacheManager): CacheService;Defined in: libs/nest-core/src/cache/services/cache.service.ts:31
Parameters
cacheManager
Cache
Returns
Methods
delete()
delete(key): Promise<boolean>;Defined in: libs/nest-core/src/cache/services/cache.service.ts:119
Delete a value from cache
This method removes a value from the cache by its key. It returns true if the operation was successful, false if there was an error.
Parameters
key
string
The unique key of the cached value to delete
Returns
Promise<boolean>
True if the operation was successful, false otherwise
Example
// Delete a cached value
const success = await cacheService.delete('user:123');
if (success) {
console.log('Cache entry successfully deleted');
} else {
console.error('Failed to delete cache entry');
}get()
get<T>(key): Promise<T | undefined>;Defined in: libs/nest-core/src/cache/services/cache.service.ts:57
Get a value from cache
This method retrieves a value from the cache by its key. It returns undefined if the key doesn't exist or if there's an error during retrieval.
Type Parameters
T
unknown
The type of the cached value
Parameters
key
string
The unique key to identify the cached value
Returns
Promise<T | undefined>
The cached value if found, undefined otherwise
Example
// Get a string value
const message = await cacheService.get<string>('greeting');
// Get a complex object
const user = await cacheService.get<User>('user:123');
if (user) {
console.log(`Found user: ${user.name}`);
} else {
console.log('User not found in cache');
}set()
set<T>(
key,
value,
ttl?): Promise<boolean>;Defined in: libs/nest-core/src/cache/services/cache.service.ts:90
Set a value in cache
This method stores a value in the cache with the specified key. An optional time-to-live (TTL) can be provided to automatically expire the cache entry.
Type Parameters
T
unknown
The type of the value to cache
Parameters
key
string
The unique key to identify the cached value
value
T
The value to store in cache
ttl?
number
Optional time-to-live in seconds
Returns
Promise<boolean>
True if the operation was successful, false otherwise
Example
// Store a simple value with no expiration
await cacheService.set('greeting', 'Hello, World!');
// Store an object with a 1-hour expiration
await cacheService.set(
'user:123',
{ id: 123, name: 'John Doe', email: '[email protected]' },
3600 // 1 hour in seconds
);HichchiMetadata
Defined in: libs/nest-core/src/metadata/metadata-storage.ts:87
Central metadata storage system for Hichchi framework
This class provides a centralized storage for metadata about DTOs, entities, and other application components. It maintains three separate stores:
- validationDtos: Maps DTO classes to their metadata
- entities: Maps entity classes to their metadata
- store: A general-purpose metadata store for any class
The class is typically accessed through the hichchiMetadata() function, which provides a singleton instance.
Example
// Register a DTO with a name
hichchiMetadata().addValidationDto(UserDto, "user");
// Register an entity
hichchiMetadata().addEntity(User, "users", ["id"]);
// Store and retrieve custom metadata
hichchiMetadata().setMetadata(User, "isSearchable", true);
const isSearchable = hichchiMetadata().getMetadata<boolean>(
User,
"isSearchable",
);See
hichchiMetadata Function to access the singleton instance
Constructors
Constructor
new HichchiMetadata(): HichchiMetadata;Returns
Methods
addEntity()
addEntity(
entity,
tableName,
unique): void;Defined in: libs/nest-core/src/metadata/metadata-storage.ts:219
Register an entity class with its metadata
This method registers an entity class with its table name and unique field constraints. It automatically generates a singular name from the table name.
Parameters
entity
Type
The entity class to register
tableName
string
The database table name for this entity
unique
string[]
Array of property names that form a unique constraint
Returns
void
Example
// Register a User entity with 'users' table and 'id' as unique field
hichchiMetadata().addEntity(User, "users", ["id"]);addValidationDto()
Implementation of the addValidationDto method Registers a DTO class with either a name or an entity class
Param
The DTO class to register
Param
The name or entity class to associate with the DTO
Call Signature
addValidationDto(dto, name): void;Defined in: libs/nest-core/src/metadata/metadata-storage.ts:113
Register a DTO class with a name
Parameters
dto
Type
The DTO class to register
name
string
The name to associate with the DTO
Returns
void
Call Signature
addValidationDto(dto, entity): void;Defined in: libs/nest-core/src/metadata/metadata-storage.ts:122
Register a DTO class with an entity class
Parameters
dto
Type
The DTO class to register
entity
Type
The entity class to associate with the DTO
Returns
void
getDtoMetaOfInstance()
getDtoMetaOfInstance(instance): HichchiMetaDto | undefined;Defined in: libs/nest-core/src/metadata/metadata-storage.ts:191
Get metadata for an object instance by finding its DTO class
This method attempts to find a registered DTO class that matches the constructor of the provided instance, and returns the metadata for that class.
Parameters
instance
unknown
The object instance to get metadata for
Returns
HichchiMetaDto | undefined
The metadata or undefined if no matching DTO is found
Example
const userDto = new UserDto();
const metadata = hichchiMetadata().getDtoMetaOfInstance(userDto);
if (metadata) {
console.log(`Found metadata for ${metadata.target.name}`);
}getEntityName()
getEntityName(entity): string | undefined;Defined in: libs/nest-core/src/metadata/metadata-storage.ts:235
Get the singular name for an entity
Parameters
entity
Type
The entity class to get the name for
Returns
string | undefined
The singular name or undefined if entity not found
Example
const entityName = hichchiMetadata().getEntityName(User);
// Returns 'user' if the entity was registered with tableName 'users'getEntityUnique()
getEntityUnique(entity): string[] | undefined;Defined in: libs/nest-core/src/metadata/metadata-storage.ts:251
Get the unique field constraints for an entity
Parameters
entity
Type
The entity class to get unique fields for
Returns
string[] | undefined
Array of unique field names or undefined if entity not found
Example
const uniqueFields = hichchiMetadata().getEntityUnique(User);
// Returns ['id'] if the entity was registered with those unique fieldsgetMetadata()
getMetadata<T>(target, propertyKey): T;Defined in: libs/nest-core/src/metadata/metadata-storage.ts:313
Retrieve custom metadata for a class
This method retrieves previously stored metadata for a class.
Type Parameters
T
The expected type of the metadata value
Parameters
target
Type
The class to retrieve metadata for
propertyKey
string
The key identifying the metadata
Returns
T
The metadata value cast to type T
Example
// Retrieve custom metadata
const isSearchable = hichchiMetadata().getMetadata<boolean>(
User,
"isSearchable",
);
const searchFields = hichchiMetadata().getMetadata<string[]>(
User,
"searchFields",
);getValidationDtoInfo()
getValidationDtoInfo(dto): HichchiMetaDtoInfo | undefined;Defined in: libs/nest-core/src/metadata/metadata-storage.ts:169
Get metadata information for a specific DTO class
Parameters
dto
Type
The DTO class to get metadata for
Returns
HichchiMetaDtoInfo | undefined
The metadata information or undefined if not found
Example
const userDtoInfo = hichchiMetadata().getValidationDtoInfo(UserDto);
if (userDtoInfo?.entity) {
console.log("UserDto is associated with an entity");
}getValidationDtos()
getValidationDtos(): Type[];Defined in: libs/nest-core/src/metadata/metadata-storage.ts:151
Get all registered DTO classes
Returns
Type[]
Array of all registered DTO classes
Example
const allDtos = hichchiMetadata().getValidationDtos();
console.log(`Found ${allDtos.length} registered DTOs`);isHichchiEntity()
isHichchiEntity(entity): boolean | undefined;Defined in: libs/nest-core/src/metadata/metadata-storage.ts:268
Check if a class is a registered Hichchi entity
Parameters
entity
Type
The class to check
Returns
boolean | undefined
True if the class is a registered entity
Example
if (hichchiMetadata().isHichchiEntity(User)) {
console.log("User is a registered entity");
}setMetadata()
setMetadata(
target,
propertyKey,
value): void;Defined in: libs/nest-core/src/metadata/metadata-storage.ts:290
Store custom metadata for a class
This method allows storing arbitrary metadata for any class. The metadata is stored with a property key for later retrieval.
Parameters
target
Type
The class to store metadata for
propertyKey
string
The key to identify this metadata
value
unknown
The metadata value to store
Returns
void
Example
// Store custom metadata
hichchiMetadata().setMetadata(User, "isSearchable", true);
hichchiMetadata().setMetadata(User, "searchFields", ["name", "email"]);ImplementationException
Defined in: libs/nest-core/src/exceptions/implementation.exception.ts:31
Exception for reporting implementation-related errors with structured details
This exception is designed for situations where there's an issue with how a component is implemented or used. It provides a structured way to report errors with a heading, message, and optional detailed description, making it easier to understand and debug implementation problems.
The exception formats the error stack trace in a more readable way, with clear separation between the heading, message, and description.
Examples
// Basic usage with heading and message
throw new ImplementationException(
"Database Connection Error",
"Failed to connect to the database",
);// Usage with heading, message, and detailed description
throw new ImplementationException(
"Configuration Error",
"Invalid Redis configuration",
"The Redis host or URL must be provided when registering the CacheModule",
);Extends
Error
Constructors
Constructor
new ImplementationException(
heading,
message,
description?): ImplementationException;Defined in: libs/nest-core/src/exceptions/implementation.exception.ts:39
Creates a new ImplementationException
Parameters
heading
string
A short title or category for the error
message
string
The main error message describing what went wrong
description?
string
Optional detailed description providing more context or troubleshooting information
Returns
Overrides
Error.constructor;Methods
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void;Defined in: node_modules/@types/node/globals.d.ts:146
Creates a .stack property on targetObject, which when accessed returns
a string representing the location in the code at which
Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
above constructorOpt, including constructorOpt, will be omitted from the
generated stack trace.
The constructorOpt argument is useful for hiding implementation
details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();Parameters
targetObject
object
constructorOpt?
Function
Returns
void
Inherited from
Error.captureStackTrace;prepareStackTrace()
static prepareStackTrace(err, stackTraces): any;Defined in: node_modules/@types/node/globals.d.ts:150
Parameters
err
Error
stackTraces
CallSite[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTrace;Properties
cause?
public
unknown
‐
Error.cause;node_modules/typescript/lib/lib.es2022.error.d.ts:26
description?
public
string
Optional detailed description providing more context or troubleshooting information
‐
libs/nest-core/src/exceptions/implementation.exception.ts:42
heading
public
string
A short title or category for the error
‐
libs/nest-core/src/exceptions/implementation.exception.ts:40
message
public
string
The main error message describing what went wrong
Error.message;libs/nest-core/src/exceptions/implementation.exception.ts:41
name
public
string
‐
Error.name;node_modules/typescript/lib/lib.es5.d.ts:1076
stack?
public
string
‐
Error.stack;node_modules/typescript/lib/lib.es5.d.ts:1078
stackTraceLimit
static
number
The Error.stackTraceLimit property specifies the number of stack frames
collected by a stack trace (whether generated by new Error().stack or
Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
will affect any stack trace captured after the value has been changed.
If set to
