# Common

#### **Common Folder Documentation**

The `common` folder in the NestJS project contains shared resources, utilities, services, and modules that are used across different parts of the application. These components provide reusable logic that can be leveraged throughout the app, promoting modularity and reducing duplication of code. Below is a breakdown of each subfolder and its purpose.

```
src/
├── common/
│   ├── config/            <-- Configuration files for the application
│   ├── databases/         <-- Database-related utilities and modules
│   ├── decorators/        <-- Custom decorators for request handling
│   ├── enums/             <-- Enum definitions for common usage
│   ├── guards/            <-- Custom guards for route protection
│   ├── interceptors/      <-- Request/response transformation and logging
│   ├── services/          <-- Reusable services used throughout the application
│   ├── swagger/           <-- Configuration for the library swagger
│   ├── tasks/             <-- Task-related utilities for background jobs
│   ├── utils/             <-- Utility functions and helpers
│   ├── common.module.ts   <-- Main entry point for the common module
```

#### **1. `config/`**

* **Purpose**: The `config/` directory contains files related to application configuration, such as environment variables and configuration modules.
* **Key Files**:
  * `env/`: Contains configuration files related to environment-specific settings. For instance, it may include settings for development, staging, and production environments.
  * `config.module.ts`: A module that imports and uses the environment configurations.

#### **2. `databases/`**

* **Purpose**: The `databases/` folder contains database-related services and modules. It typically includes database connection services and configurations for the application.
* **Key Files**:
  * `mongo.service.ts`: Handles the connection to a MongoDB database.
  * `databases.module.ts`: The module that ties together all database-related logic.

#### **3. `decorators/`**

* **Purpose**: Custom decorators used to annotate classes, methods, or parameters. These decorators allow for enhanced functionality and readability.
* **Key Files**:
  * `index.ts`: Contains a collection of all custom decorators.

Example:

```typescript
export function IsEmailVerified() {
  return applyDecorators(
    IsString(),
    MinLength(6),
    MaxLength(100),
    CustomValidator() // Custom validation logic
  );
}
```

#### **4. `enums/`**

* **Purpose**: The `enums/` folder stores common enumerations that define sets of constants for use throughout the application.
* **Key Files**:
  * `index.ts`: Contains the definitions for all enums.

**Example**:

```ts
export enum UserRole {
  ADMIN = 'admin',
  USER = 'user',
  GUEST = 'guest',
}
```

#### **5. `guards/`**

* **Purpose**: Custom guards used to secure routes or ensure specific conditions are met before allowing access to a controller or handler.
* **Key Files**:
  * `index.ts`: Centralized export for all guard files.
  * `router.guard.ts`: A guard that validates the request origin, checking headers or IP addresses before passing requests through to controllers.

#### **6. `interceptors/`**

* **Purpose**: Interceptors are used to modify incoming requests or outgoing responses. They can be used for logging, transforming data, or handling errors.
* **Key Files**:
  * `index.ts`: Centralized export for all interceptors.

**Example**:

```ts
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const now = Date.now();
    return next.handle().pipe(
      tap(() => console.log(`Request took ${Date.now() - now}ms`)),
    );
  }
}
```

#### **7. `services/`**

* **Purpose**: Contains reusable services that provide core functionality across the application, such as encryption, utility methods, or email handling.
* **Key Files**:
  * `encryption.server.ts`: A service for encryption-related tasks, such as hashing passwords.

**Example**:

```ts
@Injectable()
export class EncryptionService {
  encrypt(data: string): string {
    return bcrypt.hashSync(data, 10);
  }

  compare(data: string, hash: string): boolean {
    return bcrypt.compareSync(data, hash);
  }
}
```

#### **8. `tasks/`**

* **Purpose**: Contains modules and services related to background tasks, cron jobs, or scheduled tasks.
* **Key Files**:
  * `tasks.module.ts`: Main module to handle task scheduling and execution.

#### **9. `utils/`**

* **Purpose**: Contains general utility functions and helpers that can be used across the entire project. These utilities might include string manipulation functions, date formatting, or custom logging functionality.
* **Key Files**:
  * `index.ts`: A centralized export file for utility functions.

**Example**:

```ts
export function formatDate(date: Date): string {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
```

#### **10. `common.module.ts`**

* **Purpose**: The main module for the `common` folder, it imports all the common functionalities and makes them available across the application. This module acts as a central hub for reusable components like services, guards, and interceptors.

```
import { HttpAdapter, TranslationAdapter } from "@inlaze_techlead/inlaze-common";
import { HttpService, HttpModule } from "@nestjs/axios";
import type { DynamicModule } from "@nestjs/common";
import { Module } from "@nestjs/common";
import { EncryptionService } from "./services/encryption.service";

@Module({
  imports: [
    /** Http */
    HttpModule,
  ],
  providers: [
    {
      provide: HttpAdapter,
      useFactory: (httpService: HttpService): HttpAdapter => new HttpAdapter(httpService),
      inject: [HttpService],
    },
    TranslationAdapter,
    EncryptionService,
  ],
  exports: [HttpModule, HttpAdapter, TranslationAdapter, EncryptionService],
})
export class CommonModule {
  public static register({ isGlobal }: { isGlobal: boolean }): DynamicModule {
    return {
      module: CommonModule,
      global: isGlobal,
    };
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs-affiliates.inlaze.com/architecture/initial-folders-estructure/main-files-and-folders/common.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
