# Core Architecture

# Core Architecture

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [package.json](package.json)
- [src/domain/entities/registry.ts](src/domain/entities/registry.ts)
- [src/index.ts](src/index.ts)

</details>



The Primebrick backend is built on a modular, decorator-driven architecture designed for type safety and rapid domain modeling. It utilizes a centralized Express server that integrates a custom Domain Entity System with a generic Repository pattern, ensuring consistency across different modules like CRM and Auth.

### System Overview

The following diagram illustrates how the primary code entities interact to bootstrap the server and handle requests.

**Architecture Flow: Bootstrap to Request Handling**
```mermaid
graph TD
  subgraph "Bootstrap Phase"
    index["src/index.ts"] -- "calls" --> pool["src/db/pool.js"]
    index -- "calls" --> roleMap["loadRoleMappings()"]
    index -- "registers" --> registry["ENTITY_REGISTRY"]
  end

  subgraph "Middleware Pipeline"
    app["express()"] --> cors["cors()"]
    cors --> json["express.json()"]
    json --> cookie["cookieParser()"]
    cookie --> auth["authMiddleware"]
  end

  subgraph "Domain Layer"
    registry -- "references" --> Customer["CustomerEntity"]
    registry -- "references" --> User["UserProfileEntity"]
    Customer -- "managed by" --> Repo["Repository&lt;T&gt;"]
  end

  auth -- "routes to" --> apiRouter["apiRouter /api/v1"]
  apiRouter -- "executes" --> Repo
```
**Sources:** [src/index.ts:24-30](), [src/index.ts:184-184](), [src/domain/entities/registry.ts:14-20]()

---

### Server Bootstrap and Middleware
The application entry point is `src/index.ts` [src/index.ts:1-23](), which initializes the Express application and configures the global middleware stack. The server follows a specific mounting order to ensure the Health Check and OpenAPI documentation remain accessible while protecting functional domain routes.

*   **Global Middleware:** Includes CORS, JSON body parsing, and cookie parsing [src/index.ts:27-29]().
*   **Health Checks:** A public `/api/v1/health` endpoint verifies connectivity to both the PostgreSQL database via `checkDb()` and the Casdoor Identity Provider via `checkIdp()` [src/index.ts:154-156]().
*   **Error Handling:** A centralized `errorHandler` [src/http/error-handler.js]() catches all downstream exceptions, providing uniform JSON error responses.

For details, see [Server Bootstrap and Middleware Pipeline](#2.1).

**Sources:** [src/index.ts:154-181](), [src/index.ts:54-64]()

---

### Domain Entity System
Primebrick uses a decorator-based system to define the database schema directly in TypeScript classes. This "Code-First" approach allows the system to generate database migrations and provide type-safe data access.

**Code Entity Mapping**
```mermaid
classDiagram
    class ENTITY_REGISTRY {
        +CustomerEntity
        +UserProfileEntity
        +OrganizationEntity
    }
    class EntityDecorators {
        +@Entity(tableName)
        +@Column(options)
        +@Key()
        +@AuditableField()
    }
    ENTITY_REGISTRY ..> EntityDecorators : uses
```

*   **Registry:** All entities must be registered in the `ENTITY_REGISTRY` [src/domain/entities/registry.ts:14-20]() to be visible to the database migration tooling.
*   **Metadata:** Decorators like `@Entity` and `@Column` store metadata via `reflect-metadata` [src/domain/entities/registry.ts:5-5](), which is later used to compare the TypeScript state against the physical PostgreSQL schema.

For details, see [Domain Entity System](#2.2).

**Sources:** [src/domain/entities/registry.ts:1-21]()

---

### Repository and Query DSL
Data access is abstracted through a generic `Repository<T>` class. This layer provides a Domain Specific Language (DSL) for constructing complex PostgreSQL queries without writing raw SQL.

*   **Type Safety:** The Repository uses the metadata from the Entity System to ensure that filters, sorts, and joins refer to valid columns.
*   **Optimistic Concurrency:** Automatically handles version checking to prevent lost updates during concurrent writes.
*   **Audit Integration:** The repository works with a delta calculator to record changes in `_audit` tables whenever an entity is modified.

For details, see [Repository and Query DSL](#2.3).

**Sources:** [package.json:31-31](), [src/index.ts:12-13]()

---

### Module System and Routing
The backend is organized into functional modules (e.g., `customers`, `auth`). Each module typically contains its own router, entity definitions, and Data Access Layer (DAL).

*   **Protected Routers:** Domain routes are wrapped in `makeProtectedRouter()`, which enforces authentication [src/index.ts:164-164]().
*   **RBAC:** Routes use `rbacHandler` to check for specific `Permission` constants before allowing execution [src/index.ts:165-165]().

**Sources:** [src/index.ts:4-6](), [src/index.ts:164-179]()

---
