npm package: @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
Author: Waruna Udayanga
Latest version: 0.0.12

<!--suppress ALL -->

<div align="center">

# 🚀 @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**

[![npm version](https://img.shields.io/npm/v/@hichchi/nest-core?style=flat&color=blue)](https://www.npmjs.com/package/@hichchi/nest-core)
[![npm downloads](https://img.shields.io/npm/dm/@hichchi/nest-core?style=flat&color=green)](https://www.npmjs.com/package/@hichchi/nest-core)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/hichchidev/hichchi/blob/main/LICENSE)
[![NestJS](https://img.shields.io/badge/nestjs-11.1.3-red.svg)](https://nestjs.com/)

_Part of the [Hichchi](https://github.com/hichchidev/hichchi) ecosystem - A powerful, scalable application built with Nx workspace_

[📚 Jump to Documentation](#-api-documentation)

</div>

---

## 📋 Table of Contents

- [📦 Installation](#-installation)
- [⚡ Quick Start](#-quick-start)
- [📋 Prerequisites](#-prerequisites)
- [🌟 Overview](#-overview)
- [✨ Features](#-features)
- [🚀 Usage](#-usage)
- [🔧 Configuration Reference](#-configuration-reference)
- [🔧 Development](#-development)
- [📖 API Documentation](#-api-documentation)

---

## 📦 Installation

```bash
npm install @hichchi/nest-core
```

## ⚡ Quick Start

Get up and running with essential NestJS utilities in just a few minutes:

```typescript
// 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

```bash
# 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/redis
```

### Internal Dependencies

This package depends on:

```bash
npm install @hichchi/nest-connector @hichchi/utils
```

### Optional Dependencies

For enhanced features:

```bash
# For HTTP client functionality
npm install axios

# For advanced validation
npm install class-validator class-transformer
```

### System 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.

```typescript
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.

```typescript
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.

```typescript
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.

```typescript
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.

```typescript
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.

```typescript
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.

```typescript
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.

```typescript
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

```typescript
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

```typescript
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

```typescript
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

```bash
nx build nest-core
```

Compile and bundle the core utilities for production use.

### Testing

```bash
nx test nest-core
```

Run comprehensive unit tests powered by [Jest](https://jestjs.io).

---

<div align="center">

**Made with ❤️ by [Hichchi Dev](https://github.com/hichchidev)**

[![Hichchi Ecosystem](https://img.shields.io/badge/🏠_Hichchi_Ecosystem-blue)](https://github.com/hichchidev/hichchi)
[![Report Bug](https://img.shields.io/badge/🐛_Report_Bug-red)](https://github.com/hichchidev/hichchi/issues)
[![Request Feature](https://img.shields.io/badge/✨_Request_Feature-green)](https://github.com/hichchidev/hichchi/issues)

_Accelerating NestJS development with essential bootstrap, caching, logging, middleware, and enterprise-grade utilities_

</div>

---

# 📖 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.

<!-- TypeDoc generated documentation will be appended below this point -->

---

## 📋 API Table of Contents

- [Classes](#classes)
  - [AllExceptionsFilter](#allexceptionsfilter)
  - [AxiosHttpService](#axioshttpservice-1)
  - [CacheModule](#cachemodule)
  - [CacheService](#cacheservice)
  - [HichchiMetadata](#hichchimetadata)
  - [ImplementationException](#implementationexception)
  - [JsonArrayFileTransport](#jsonarrayfiletransport)
  - [JsonBodyMiddleware](#jsonbodymiddleware)
  - [LoggerService](#loggerservice-1)
  - [PaginatedResponse](#paginatedresponse)
  - [RawBodyMiddleware](#rawbodymiddleware)
  - [RedisConfigException](#redisconfigexception)
  - [TransformInterceptor](#transforminterceptor)
- [Functions](#functions)
  - [BooleanTransformer()](#booleantransformer)
  - [BooleanTransformerWithDefault()](#booleantransformerwithdefault)
  - [colorize()](#colorize)
  - [consoleFormat()](#consoleformat)
  - [DateTransformer()](#datetransformer)
  - [Dto()](#dto)
  - [errorFileFormat()](#errorfileformat)
  - [FileFormFieldTransformer()](#fileformfieldtransformer)
  - [FileOrTextFormFieldTransformer()](#fileortextformfieldtransformer)
  - [findFirstConstraint()](#findfirstconstraint)
  - [formatMessage()](#formatmessage)
  - [generateValidationErrorResponse()](#generatevalidationerrorresponse)
  - [getGlobal()](#getglobal)
  - [hichchiBootstrap()](#hichchibootstrap-1)
  - [hichchiMetadata()](#hichchimetadata-1)
  - [httpExceptionFilter()](#httpexceptionfilter)
  - [isJson()](#isjson)
  - [isOriginAllowed()](#isoriginallowed)
  - [isRandomHexToken()](#israndomhextoken)
  - [IsRandomHexToken()](#israndomhextoken-1)
  - [IsVerifyToken()](#isverifytoken)
  - [MultiValueFormFieldTransformer()](#multivalueformfieldtransformer)
  - [throwValidationErrors()](#throwvalidationerrors)
  - [toErrorObject()](#toerrorobject)
  - [toErrString()](#toerrstring)
  - [toJSON()](#tojson)
  - [toString()](#tostring)
  - [UseTransformInterceptor()](#usetransforminterceptor)
  - [validateDto()](#validatedto)
  - [validationPipeExceptionFactory()](#validationpipeexceptionfactory)
- [Interfaces](#interfaces)
  - [Colorizer()](#colorizer)
  - [ColorScheme](#colorscheme)
  - [CommonRedisOptions](#commonredisoptions)
  - [InfoObject](#infoobject)
  - [IViewDto](#iviewdto)
  - [LogEntry](#logentry)
  - [LoggerOptions](#loggeroptions)
  - [MulterFile](#multerfile)
  - [NestLikeFormatOptions](#nestlikeformatoptions)
  - [RedisOptionsWithHost](#redisoptionswithhost)
  - [RedisOptionsWithUrl](#redisoptionswithurl)
- [Type Aliases](#type-aliases)
  - [LogParam](#logparam)
  - [RedisOptions](#redisoptions)
- [Variables](#variables)
  - [CACHE_OPTIONS](#cache_options)
  - [clc](#clc)
  - [colorScheme](#colorscheme-1)
  - [DEFAULT_PORT](#default_port)
  - [defaultOptions](#defaultoptions)
  - [IS_RANDOM_HEX_TOKEN](#is_random_hex_token)
  - [IS_VERIFY_TOKEN](#is_verify_token)

## Classes

### AllExceptionsFilter

Defined in: [libs/nest-core/src/filters/http-exception.filter.ts:43](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/filters/http-exception.filter.ts#L43)

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

```TypeScript
// 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](#httpexceptionfilter) The utility function that processes exceptions
- ErrorResponse The standardized error response structure

#### Extends

- `BaseExceptionFilter`

#### Constructors

##### Constructor

```ts
new AllExceptionsFilter(applicationRef?): AllExceptionsFilter;
```

Defined in: node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:8

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`applicationRef?`

</td>
<td>

`HttpServer`<`any`, `any`, `any`>

</td>
</tr>
</tbody>
</table>

###### Returns

[`AllExceptionsFilter`](#allexceptionsfilter)

###### Inherited from

```ts
BaseExceptionFilter.constructor;
```

#### Methods

##### catch()

```ts
catch(exception, host): void;
```

Defined in: [libs/nest-core/src/filters/http-exception.filter.ts:64](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/filters/http-exception.filter.ts#L64)

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:

1. Extracts the HTTP request from the ArgumentsHost
2. Passes the exception, request, and true (to enable logging) to httpExceptionFilter
3. Passes the processed exception to the parent class's catch method

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`exception`

</td>
<td>

`unknown`

</td>
<td>

The exception object thrown in the application

</td>
</tr>
<tr>
<td>

`host`

</td>
<td>

`ArgumentsHost`

</td>
<td>

The arguments host object containing the execution context

</td>
</tr>
</tbody>
</table>

###### Returns

`void`

###### See

- [httpExceptionFilter](#httpexceptionfilter) The utility function that processes exceptions
- BaseExceptionFilter.catch The parent class's catch method

###### Overrides

```ts
BaseExceptionFilter.catch;
```

##### handleUnknownError()

```ts
handleUnknownError(
   exception,
   host,
   applicationRef): void;
```

Defined in: node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:10

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`exception`

</td>
<td>

`any`

</td>
</tr>
<tr>
<td>

`host`

</td>
<td>

`ArgumentsHost`

</td>
</tr>
<tr>
<td>

`applicationRef`

</td>
<td>

| `HttpServer`<`any`, `any`, `any`> | `AbstractHttpAdapter`<`any`, `any`, `any`>

</td>
</tr>
</tbody>
</table>

###### Returns

`void`

###### Inherited from

```ts
BaseExceptionFilter.handleUnknownError;
```

##### isExceptionObject()

```ts
isExceptionObject(err): err is Error;
```

Defined in: node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:11

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`err`

</td>
<td>

`any`

</td>
</tr>
</tbody>
</table>

###### Returns

`err is Error`

###### Inherited from

```ts
BaseExceptionFilter.isExceptionObject;
```

##### isHttpError()

```ts
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

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`err`

</td>
<td>

`any`

</td>
<td>

error object

</td>
</tr>
</tbody>
</table>

###### Returns

`err is { message: string; statusCode: number }`

###### Inherited from

```ts
BaseExceptionFilter.isHttpError;
```

#### Properties

<table>
<thead>
<tr>
<th>Property</th>
<th>Modifier</th>
<th>Type</th>
<th>Inherited from</th>
<th>Defined in</th>
</tr>
</thead>
<tbody>
<tr>
<td>

<a id="property-applicationref"></a> `applicationRef?`

</td>
<td>

`readonly`

</td>
<td>

`HttpServer`<`any`, `any`, `any`>

</td>
<td>

```ts
BaseExceptionFilter.applicationRef;
```

</td>
<td>

node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:5

</td>
</tr>
<tr>
<td>

<a id="property-httpadapterhost"></a> `httpAdapterHost?`

</td>
<td>

`readonly`

</td>
<td>

`HttpAdapterHost`<`AbstractHttpAdapter`<`any`, `any`, `any`>>

</td>
<td>

```ts
BaseExceptionFilter.httpAdapterHost;
```

</td>
<td>

node_modules/@nestjs/core/exceptions/base-exception-filter.d.ts:7

</td>
</tr>
</tbody>
</table>

---

### AxiosHttpService

Defined in: [libs/nest-core/src/services/axios-http.service.ts:49](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/services/axios-http.service.ts#L49)

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

```typescript
// 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

```ts
new AxiosHttpService(httpService): AxiosHttpService;
```

Defined in: [libs/nest-core/src/services/axios-http.service.ts:50](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/services/axios-http.service.ts#L50)

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`httpService`

</td>
<td>

`HttpService`

</td>
</tr>
</tbody>
</table>

###### Returns

[`AxiosHttpService`](#axioshttpservice)

#### Methods

##### delete()

```ts
delete<T>(url, config?): Promise<T>;
```

Defined in: [libs/nest-core/src/services/axios-http.service.ts:322](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/services/axios-http.service.ts#L322)

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

<table>
<thead>
<tr>
<th>Type Parameter</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`T`

</td>
<td>

The expected type of the response data

</td>
</tr>
</tbody>
</table>

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`url`

</td>
<td>

`string`

</td>
<td>

The URL to send the request to

</td>
</tr>
<tr>
<td>

`config?`

</td>
<td>

`AxiosRequestConfig`<`any`>

</td>
<td>

Optional Axios request configuration

</td>
</tr>
</tbody>
</table>

###### 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

```typescript
// 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()

```ts
get<T>(url, config?): Promise<T>;
```

Defined in: [libs/nest-core/src/services/axios-http.service.ts:80](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/services/axios-http.service.ts#L80)

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

<table>
<thead>
<tr>
<th>Type Parameter</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`T`

</td>
<td>

The expected type of the response data

</td>
</tr>
</tbody>
</table>

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`url`

</td>
<td>

`string`

</td>
<td>

The URL to send the request to

</td>
</tr>
<tr>
<td>

`config?`

</td>
<td>

`AxiosRequestConfig`<`any`>

</td>
<td>

Optional Axios request configuration

</td>
</tr>
</tbody>
</table>

###### 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

```typescript
// 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()

```ts
patch<T, D>(
   url,
   data?,
config?): Promise<T>;
```

Defined in: [libs/nest-core/src/services/axios-http.service.ts:266](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/services/axios-http.service.ts#L266)

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

<table>
<thead>
<tr>
<th>Type Parameter</th>
<th>Default type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`T`

</td>
<td>

‐

</td>
<td>

The expected type of the response data

</td>
</tr>
<tr>
<td>

`D`

</td>
<td>

`any`

</td>
<td>

The type of the request data (defaults to any)

</td>
</tr>
</tbody>
</table>

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`url`

</td>
<td>

`string`

</td>
<td>

The URL to send the request to

</td>
</tr>
<tr>
<td>

`data?`

</td>
<td>

`D`

</td>
<td>

Optional data to send in the request body

</td>
</tr>
<tr>
<td>

`config?`

</td>
<td>

`AxiosRequestConfig`<`any`>

</td>
<td>

Optional Axios request configuration

</td>
</tr>
</tbody>
</table>

###### 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

```typescript
// 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()

```ts
post<T, D>(
   url,
   data?,
config?): Promise<T>;
```

Defined in: [libs/nest-core/src/services/axios-http.service.ts:138](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/services/axios-http.service.ts#L138)

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

<table>
<thead>
<tr>
<th>Type Parameter</th>
<th>Default type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`T`

</td>
<td>

‐

</td>
<td>

The expected type of the response data

</td>
</tr>
<tr>
<td>

`D`

</td>
<td>

`any`

</td>
<td>

The type of the request data (defaults to any)

</td>
</tr>
</tbody>
</table>

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`url`

</td>
<td>

`string`

</td>
<td>

The URL to send the request to

</td>
</tr>
<tr>
<td>

`data?`

</td>
<td>

`D`

</td>
<td>

Optional data to send in the request body

</td>
</tr>
<tr>
<td>

`config?`

</td>
<td>

`AxiosRequestConfig`<`any`>

</td>
<td>

Optional Axios request configuration

</td>
</tr>
</tbody>
</table>

###### 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

```typescript
// 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: "john@example.com" },
);

// Post with additional headers
const response = await httpService.post<ApiResponse, FormData>(
  "https://api.example.com/upload",
  formData,
  { headers: { "Content-Type": "multipart/form-data" } },
);
```

##### put()

```ts
put<T, D>(
   url,
   data?,
config?): Promise<T>;
```

Defined in: [libs/nest-core/src/services/axios-http.service.ts:204](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/services/axios-http.service.ts#L204)

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

<table>
<thead>
<tr>
<th>Type Parameter</th>
<th>Default type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`T`

</td>
<td>

‐

</td>
<td>

The expected type of the response data

</td>
</tr>
<tr>
<td>

`D`

</td>
<td>

`any`

</td>
<td>

The type of the request data (defaults to any)

</td>
</tr>
</tbody>
</table>

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`url`

</td>
<td>

`string`

</td>
<td>

The URL to send the request to

</td>
</tr>
<tr>
<td>

`data?`

</td>
<td>

`D`

</td>
<td>

Optional data to send in the request body

</td>
</tr>
<tr>
<td>

`config?`

</td>
<td>

`AxiosRequestConfig`<`any`>

</td>
<td>

Optional Axios request configuration

</td>
</tr>
</tbody>
</table>

###### 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

```typescript
// 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: "john@example.com",
    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](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/cache/cache.module.ts#L53)

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

```typescript
// In your app module
@Module({
  imports: [
    CacheModule.register({
      host: "localhost",
      port: 6379,
      ttl: 3600,
      prefix: "myapp:",
    }),
  ],
})
export class AppModule {}
```

```typescript
// Using with a Redis URL
@Module({
  imports: [
    CacheModule.register({
      url: "redis://username:password@redis.example.com:6379",
      ttl: 86400, // 1 day
      lruSize: 1000,
    }),
  ],
})
export class AppModule {}
```

#### Constructors

##### Constructor

```ts
new CacheModule(): CacheModule;
```

###### Returns

[`CacheModule`](#cachemodule)

#### Methods

##### register()

```ts
static register(options): DynamicModule;
```

Defined in: [libs/nest-core/src/cache/cache.module.ts:89](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/cache/cache.module.ts#L89)

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:

1. An in-memory LRU cache for frequently accessed items
2. 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

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`options`

</td>
<td>

[`RedisOptions`](#redisoptions)

</td>
<td>

Redis connection and caching options

</td>
</tr>
</tbody>
</table>

###### Returns

`DynamicModule`

A NestJS dynamic module configured for caching

###### Throws

If neither host nor url is provided in options

###### Examples

```typescript
// Register with host-based configuration
CacheModule.register({
  host: "localhost",
  port: 6379,
  ttl: 3600,
});
```

```typescript
// 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](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/cache/services/cache.service.ts#L30)

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

```TypeScript
// 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](#cachemodule) The module that provides this service

#### Constructors

##### Constructor

```ts
new CacheService(cacheManager): CacheService;
```

Defined in: [libs/nest-core/src/cache/services/cache.service.ts:31](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/cache/services/cache.service.ts#L31)

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`cacheManager`

</td>
<td>

`Cache`

</td>
</tr>
</tbody>
</table>

###### Returns

[`CacheService`](#cacheservice)

#### Methods

##### delete()

```ts
delete(key): Promise<boolean>;
```

Defined in: [libs/nest-core/src/cache/services/cache.service.ts:119](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/cache/services/cache.service.ts#L119)

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

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`key`

</td>
<td>

`string`

</td>
<td>

The unique key of the cached value to delete

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`boolean`>

True if the operation was successful, false otherwise

###### Example

```TypeScript
// 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()

```ts
get<T>(key): Promise<T | undefined>;
```

Defined in: [libs/nest-core/src/cache/services/cache.service.ts:57](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/cache/services/cache.service.ts#L57)

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

<table>
<thead>
<tr>
<th>Type Parameter</th>
<th>Default type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`T`

</td>
<td>

`unknown`

</td>
<td>

The type of the cached value

</td>
</tr>
</tbody>
</table>

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`key`

</td>
<td>

`string`

</td>
<td>

The unique key to identify the cached value

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`T` | `undefined`>

The cached value if found, undefined otherwise

###### Example

```TypeScript
// 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()

```ts
set<T>(
   key,
   value,
ttl?): Promise<boolean>;
```

Defined in: [libs/nest-core/src/cache/services/cache.service.ts:90](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/cache/services/cache.service.ts#L90)

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

<table>
<thead>
<tr>
<th>Type Parameter</th>
<th>Default type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`T`

</td>
<td>

`unknown`

</td>
<td>

The type of the value to cache

</td>
</tr>
</tbody>
</table>

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`key`

</td>
<td>

`string`

</td>
<td>

The unique key to identify the cached value

</td>
</tr>
<tr>
<td>

`value`

</td>
<td>

`T`

</td>
<td>

The value to store in cache

</td>
</tr>
<tr>
<td>

`ttl?`

</td>
<td>

`number`

</td>
<td>

Optional time-to-live in seconds

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`boolean`>

True if the operation was successful, false otherwise

###### Example

```TypeScript
// 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: 'john@example.com' },
  3600 // 1 hour in seconds
);
```

---

### HichchiMetadata

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:87](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L87)

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:

1. validationDtos: Maps DTO classes to their metadata
2. entities: Maps entity classes to their metadata
3. store: A general-purpose metadata store for any class

The class is typically accessed through the hichchiMetadata() function,
which provides a singleton instance.

#### Example

```typescript
// 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](#hichchimetadata-1) Function to access the singleton instance

#### Constructors

##### Constructor

```ts
new HichchiMetadata(): HichchiMetadata;
```

###### Returns

[`HichchiMetadata`](#hichchimetadata)

#### Methods

##### addEntity()

```ts
addEntity(
   entity,
   tableName,
   unique): void;
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:219](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L219)

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

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`entity`

</td>
<td>

`Type`

</td>
<td>

The entity class to register

</td>
</tr>
<tr>
<td>

`tableName`

</td>
<td>

`string`

</td>
<td>

The database table name for this entity

</td>
</tr>
<tr>
<td>

`unique`

</td>
<td>

`string`\[]

</td>
<td>

Array of property names that form a unique constraint

</td>
</tr>
</tbody>
</table>

###### Returns

`void`

###### Example

```typescript
// 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

```ts
addValidationDto(dto, name): void;
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:113](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L113)

Register a DTO class with a name

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`dto`

</td>
<td>

`Type`

</td>
<td>

The DTO class to register

</td>
</tr>
<tr>
<td>

`name`

</td>
<td>

`string`

</td>
<td>

The name to associate with the DTO

</td>
</tr>
</tbody>
</table>

###### Returns

`void`

###### Call Signature

```ts
addValidationDto(dto, entity): void;
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:122](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L122)

Register a DTO class with an entity class

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`dto`

</td>
<td>

`Type`

</td>
<td>

The DTO class to register

</td>
</tr>
<tr>
<td>

`entity`

</td>
<td>

`Type`

</td>
<td>

The entity class to associate with the DTO

</td>
</tr>
</tbody>
</table>

###### Returns

`void`

##### getDtoMetaOfInstance()

```ts
getDtoMetaOfInstance(instance): HichchiMetaDto | undefined;
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:191](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L191)

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

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`instance`

</td>
<td>

`unknown`

</td>
<td>

The object instance to get metadata for

</td>
</tr>
</tbody>
</table>

###### Returns

`HichchiMetaDto` | `undefined`

The metadata or undefined if no matching DTO is found

###### Example

```typescript
const userDto = new UserDto();
const metadata = hichchiMetadata().getDtoMetaOfInstance(userDto);
if (metadata) {
  console.log(`Found metadata for ${metadata.target.name}`);
}
```

##### getEntityName()

```ts
getEntityName(entity): string | undefined;
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:235](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L235)

Get the singular name for an entity

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`entity`

</td>
<td>

`Type`

</td>
<td>

The entity class to get the name for

</td>
</tr>
</tbody>
</table>

###### Returns

`string` | `undefined`

The singular name or undefined if entity not found

###### Example

```typescript
const entityName = hichchiMetadata().getEntityName(User);
// Returns 'user' if the entity was registered with tableName 'users'
```

##### getEntityUnique()

```ts
getEntityUnique(entity): string[] | undefined;
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:251](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L251)

Get the unique field constraints for an entity

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`entity`

</td>
<td>

`Type`

</td>
<td>

The entity class to get unique fields for

</td>
</tr>
</tbody>
</table>

###### Returns

`string`\[] | `undefined`

Array of unique field names or undefined if entity not found

###### Example

```typescript
const uniqueFields = hichchiMetadata().getEntityUnique(User);
// Returns ['id'] if the entity was registered with those unique fields
```

##### getMetadata()

```ts
getMetadata<T>(target, propertyKey): T;
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:313](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L313)

Retrieve custom metadata for a class

This method retrieves previously stored metadata for a class.

###### Type Parameters

<table>
<thead>
<tr>
<th>Type Parameter</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`T`

</td>
<td>

The expected type of the metadata value

</td>
</tr>
</tbody>
</table>

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`target`

</td>
<td>

`Type`

</td>
<td>

The class to retrieve metadata for

</td>
</tr>
<tr>
<td>

`propertyKey`

</td>
<td>

`string`

</td>
<td>

The key identifying the metadata

</td>
</tr>
</tbody>
</table>

###### Returns

`T`

The metadata value cast to type T

###### Example

```typescript
// Retrieve custom metadata
const isSearchable = hichchiMetadata().getMetadata<boolean>(
  User,
  "isSearchable",
);
const searchFields = hichchiMetadata().getMetadata<string[]>(
  User,
  "searchFields",
);
```

##### getValidationDtoInfo()

```ts
getValidationDtoInfo(dto): HichchiMetaDtoInfo | undefined;
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:169](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L169)

Get metadata information for a specific DTO class

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`dto`

</td>
<td>

`Type`

</td>
<td>

The DTO class to get metadata for

</td>
</tr>
</tbody>
</table>

###### Returns

`HichchiMetaDtoInfo` | `undefined`

The metadata information or undefined if not found

###### Example

```typescript
const userDtoInfo = hichchiMetadata().getValidationDtoInfo(UserDto);
if (userDtoInfo?.entity) {
  console.log("UserDto is associated with an entity");
}
```

##### getValidationDtos()

```ts
getValidationDtos(): Type[];
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:151](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L151)

Get all registered DTO classes

###### Returns

`Type`\[]

Array of all registered DTO classes

###### Example

```typescript
const allDtos = hichchiMetadata().getValidationDtos();
console.log(`Found ${allDtos.length} registered DTOs`);
```

##### isHichchiEntity()

```ts
isHichchiEntity(entity): boolean | undefined;
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:268](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L268)

Check if a class is a registered Hichchi entity

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`entity`

</td>
<td>

`Type`

</td>
<td>

The class to check

</td>
</tr>
</tbody>
</table>

###### Returns

`boolean` | `undefined`

True if the class is a registered entity

###### Example

```typescript
if (hichchiMetadata().isHichchiEntity(User)) {
  console.log("User is a registered entity");
}
```

##### setMetadata()

```ts
setMetadata(
   target,
   propertyKey,
   value): void;
```

Defined in: [libs/nest-core/src/metadata/metadata-storage.ts:290](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/metadata/metadata-storage.ts#L290)

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

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`target`

</td>
<td>

`Type`

</td>
<td>

The class to store metadata for

</td>
</tr>
<tr>
<td>

`propertyKey`

</td>
<td>

`string`

</td>
<td>

The key to identify this metadata

</td>
</tr>
<tr>
<td>

`value`

</td>
<td>

`unknown`

</td>
<td>

The metadata value to store

</td>
</tr>
</tbody>
</table>

###### Returns

`void`

###### Example

```typescript
// 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](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/exceptions/implementation.exception.ts#L31)

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

```typescript
// Basic usage with heading and message
throw new ImplementationException(
  "Database Connection Error",
  "Failed to connect to the database",
);
```

```typescript
// 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

```ts
new ImplementationException(
   heading,
   message,
   description?): ImplementationException;
```

Defined in: [libs/nest-core/src/exceptions/implementation.exception.ts:39](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/exceptions/implementation.exception.ts#L39)

Creates a new ImplementationException

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`heading`

</td>
<td>

`string`

</td>
<td>

A short title or category for the error

</td>
</tr>
<tr>
<td>

`message`

</td>
<td>

`string`

</td>
<td>

The main error message describing what went wrong

</td>
</tr>
<tr>
<td>

`description?`

</td>
<td>

`string`

</td>
<td>

Optional detailed description providing more context or troubleshooting information

</td>
</tr>
</tbody>
</table>

###### Returns

[`ImplementationException`](#implementationexception)

###### Overrides

```ts
Error.constructor;
```

#### Methods

##### captureStackTrace()

```ts
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.

```js
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:

```js
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

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`targetObject`

</td>
<td>

`object`

</td>
</tr>
<tr>
<td>

`constructorOpt?`

</td>
<td>

`Function`

</td>
</tr>
</tbody>
</table>

###### Returns

`void`

###### Inherited from

```ts
Error.captureStackTrace;
```

##### prepareStackTrace()

```ts
static prepareStackTrace(err, stackTraces): any;
```

Defined in: node_modules/@types/node/globals.d.ts:150

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`err`

</td>
<td>

`Error`

</td>
</tr>
<tr>
<td>

`stackTraces`

</td>
<td>

`CallSite`\[]

</td>
</tr>
</tbody>
</table>

###### Returns

`any`

###### See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

###### Inherited from

```ts
Error.prepareStackTrace;
```

#### Properties

<table>
<thead>
<tr>
<th>Property</th>
<th>Modifier</th>
<th>Type</th>
<th>Description</th>
<th>Inherited from</th>
<th>Defined in</th>
</tr>
</thead>
<tbody>
<tr>
<td>

<a id="property-cause"></a> `cause?`

</td>
<td>

`public`

</td>
<td>

`unknown`

</td>
<td>

‐

</td>
<td>

```ts
Error.cause;
```

</td>
<td>

node_modules/typescript/lib/lib.es2022.error.d.ts:26

</td>
</tr>
<tr>
<td>

<a id="property-description"></a> `description?`

</td>
<td>

`public`

</td>
<td>

`string`

</td>
<td>

Optional detailed description providing more context or troubleshooting information

</td>
<td>

‐

</td>
<td>

[libs/nest-core/src/exceptions/implementation.exception.ts:42](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/exceptions/implementation.exception.ts#L42)

</td>
</tr>
<tr>
<td>

<a id="property-heading"></a> `heading`

</td>
<td>

`public`

</td>
<td>

`string`

</td>
<td>

A short title or category for the error

</td>
<td>

‐

</td>
<td>

[libs/nest-core/src/exceptions/implementation.exception.ts:40](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/exceptions/implementation.exception.ts#L40)

</td>
</tr>
<tr>
<td>

<a id="property-message"></a> `message`

</td>
<td>

`public`

</td>
<td>

`string`

</td>
<td>

The main error message describing what went wrong

</td>
<td>

```ts
Error.message;
```

</td>
<td>

[libs/nest-core/src/exceptions/implementation.exception.ts:41](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-core/src/exceptions/implementation.exception.ts#L41)

</td>
</tr>
<tr>
<td>

<a id="property-name"></a> `name`

</td>
<td>

`public`

</td>
<td>

`string`

</td>
<td>

‐

</td>
<td>

```ts
Error.name;
```

</td>
<td>

node_modules/typescript/lib/lib.es5.d.ts:1076

</td>
</tr>
<tr>
<td>

<a id="property-stack"></a> `stack?`

</td>
<td>

`public`

</td>
<td>

`string`

</td>
<td>

‐

</td>
<td>

```ts
Error.stack;
```

</td>
<td>

node_modules/typescript/lib/lib.es5.d.ts:1078

</td>
</tr>
<tr>
<td>

<a id="property-stacktracelimit"></a> `stackTraceLimit`

</td>
<td>

`static`

</td>
<td>

`number`

</td>
<td>

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