# zerocyber/nestjs-template architecture

> Architecture diagram of the GitHub repository zerocyber/nestjs-template, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-04-30). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/zerocyber/nestjs-template
- Repository: https://github.com/zerocyber/nestjs-template

## Overview

아래 지침은 제공된 프로젝트(“NestJS 기본 템플릿”)의 구조와 목적을 바탕으로 ‘최적의 시스템 아키텍처 다이어그램’을 그리기 위한 구체적인 가이드입니다. 주요 컴포넌트, 이들 간의 관계, 및 다이어그램에서 강조해야 할 설계 원칙 등을 단계별로 설명합니다.

##### 프로젝트 타입 및 목적 파악
- **프로젝트 타입**: NestJS 기반 백엔드 API 템플릿
- **주요 기능**:
- 인증(AuthModule: 로컬 인증, QR 인증, 세션 시리얼라이저, 각종 Guard)
- 투두 관리(TodosModule)
- 유저 관리(UserModule)
- Prisma ORM을 이용한 RDB 접근(PrismaService + schema.prisma)
- Redis 세션/캐시(공통(Common) 모듈 내 RedisProvider)
- 로깅(Logging Middleware/Interceptor)
- **사용 사례**: 다른 NestJS 프로젝트에 쉽게 재사용 가능한 ‘보일러플레이트’로, 빠른 시작과 표준화된 아키텍처 제공

##### 파일 구조 분석
- src/app.module.ts: 루트 모듈, 전역 설정
- src/auth, src/todos, src/user: Feature 모듈, 각 모듈별 Controller, Service, DTO, Guard, Strategy 등
- src/common: 전역 공통 기능(Interceptor, Middleware, Redis 모듈/Provider)
- src/prisma.service.ts + prisma/schema.prisma: DB 접속 및 모델 정의
- test/, *.spec.ts: 유닛·E2E 테스트 스캐폴드

##### README에서 추가 인사이트
- DB 연결은 .env + SSH 터널링
- 환경별(로컬 vs 원격) 데이터베이스 접속 가이드

##### 시스템 디자인 다이어그램 작성 가이드
a. 메인 컴포넌트 식별
1) External Clients (웹/모바일 프론트엔드, Postman 등)
2) NestJS Application (HTTP 서버)
- Controllers (Auth, Todos, User)
- Services (AuthService, TodosService, UserService, PrismaService)
- Guards & Strategies
- Middleware & Interceptors
- RedisModule (Provider)
3) Datastores
- Relational DB (PostgreSQL/MySQL 등 via Prisma)
- Redis (세션/캐시)
4) 테스트 프레임워크 (Jest, E2E 테스트) – 다이어그램 우측 하단에 별도 표기 가능
b. 컴포넌트 간 상호작용
1) HTTP 요청 → NestJS Middleware (Logging → Authentication Guard)
2) Controller → Service 호출 → PrismaService → RDB CRUD
3) AuthService ↔ RedisProvider (Session 저장/조회)
4) 모든 요청/응답 흐름에 Interceptor(로깅) 적용
c. 아키텍처 패턴 및 설계 원칙
- 모듈화(Modularity): Feature별로 모듈 분리
- 계층화(Layers): Controller → Service → Database
- DI(Dependency Injection): PrismaService, RedisProvider 등
- Cross-cutting Concerns: Logging, Authentication Guard, Interceptor
d. 핵심 기술/라이브러리
- NestJS Framework
- Prisma ORM
- Redis
- Passport 전략(local, QR)
- Jest (테스트)

##### 프로젝트 유형별 다이어그램 튜닝
- **백엔드 API**:
- 요청 흐름 집중: External → HTTP Server → Guards → Controllers → Services → DB/Redis
- 모듈 간 종속성(Imports)을 화살표로 표시
- **공통 모듈**:
- RedisModule과 PrismaService는 전역에 연결되는 ‘파이프라인’ 컴포넌트로 강조
- **테스트**:
- E2E 테스트는 실제 데이터베이스/Redis 흉내를 내며 전체 플로우를 검증하는 시나리오로 간략 표기

##### 다이어그램 작성 시 포함 요소
- 컴포넌트 이름(Controller, Service, Module, DB)
- 방향성 화살표(HTTP → Controller, Controller → Service, Service → DB/Redis)
- 색상/도형 구분:
- 외부(클라이언트): 파란색 구름 모양
- NestJS 모듈/컴포넌트: 녹색 박스
- 서비스/비즈니스 로직: 주황색 박스
- 데이터 저장소: 보라색 실린더(관계형 DB), 사각 Redis 아이콘
- 테스트 요소: 회색 점선 박스

##### 최종 다이어그램 예시 구성
[Clients]
|
v
[NestJS HTTP Server]
|-- Middleware (Logging)
|-- Guards (LocalAuthGuard, QrAuthGuard, AuthenticatedGuard)
|-- Interceptor (LoggingInterceptor)
|
+--> [AuthController] --> [AuthService] --> [Redis (Session)]
+--> [UserController] --> [UserService] --> [PrismaService] --> [RDB]
+--> [TodosController] --> [TodosService] --> [PrismaService] --> [RDB]
|
+--> [CommonModule: RedisModule, PrismaModule]

- 각 컴포넌트마다 레이블, 입·출력 포트를 명시
- 모듈 간 의존성 화살표로 연결
- 공통 기능(Logging, Redis, Prisma)은 중간 계층으로 묶어서 표현

## Diagram (Mermaid)

```mermaid
flowchart TB
    ExternalClients["External Clients"]:::external
    ExternalClients --> Main
    subgraph "NestJS Application"
        Main["Main (HTTP Server Entry)"]:::module
        AppModule["AppModule"]:::module
        AppService["AppService"]:::service
        LoggingMiddleware["LoggingMiddleware"]:::cross
        LoggingInterceptor["LoggingInterceptor"]:::cross
        subgraph "Auth Module"
            AuthController["AuthController"]:::module
            AuthService["AuthService"]:::service
            SessionSerializer["SessionSerializer"]:::service
            LocalAuthGuard["LocalAuthGuard"]:::service
            QrAuthGuard["QrAuthGuard"]:::service
            AuthenticatedGuard["AuthenticatedGuard"]:::service
            LocalStrategy["LocalStrategy"]:::service
            QRStrategy["QRStrategy"]:::service
        end
        subgraph "User Module"
            UserController["UserController"]:::module
            UserService["UserService"]:::service
            CreateUserDto["CreateUserDto"]:::data
            UpdateUserDto["UpdateUserDto"]:::data
        end
        subgraph "Todos Module"
            TodosController["TodosController"]:::module
            TodosService["TodosService"]:::service
            CreateTodoDto["CreateTodoDto"]:::data
            UpdateTodoDto["UpdateTodoDto"]:::data
        end
        RedisModule["RedisModule"]:::module
        RedisProvider["RedisProvider"]:::service
        PrismaService["PrismaService"]:::service
    end
    subgraph "Data Stores"
        RDB[(Relational DB)]:::db
        Redis[(Redis)]:::db
    end
    subgraph "Tests"
        UnitTests["Unit Tests"]:::test
        E2ETests["E2E Tests"]:::test
    end

    Main --> AppModule
    AppModule --> AppService
    AppModule --> LoggingMiddleware
    AppModule --> LoggingInterceptor
    AppModule --> RedisModule
    AppModule --> PrismaService
    AppModule --> AuthController
    AppModule --> UserController
    AppModule --> TodosController

    Main --> LoggingMiddleware --> LoggingInterceptor
    LoggingInterceptor --> LocalAuthGuard
    LoggingInterceptor --> QrAuthGuard
    LoggingInterceptor --> AuthenticatedGuard

    LocalAuthGuard --> AuthController
    QrAuthGuard --> AuthController
    AuthenticatedGuard --> UserController
    AuthenticatedGuard --> TodosController

    AuthController --> AuthService
    AuthService --> RedisProvider
    AuthService --> SessionSerializer

    UserController --> UserService
    UserService --> PrismaService
    TodosController --> TodosService
    TodosService --> PrismaService

    PrismaService --> RDB
    RedisProvider --> Redis
    RedisModule --> RedisProvider

    UnitTests -.-> AppModule
    UnitTests -.-> PrismaService
    E2ETests -.-> ExternalClients
    E2ETests -.-> RDB
    E2ETests -.-> Redis

    click Main "https://github.com/zerocyber/nestjs-template/blob/master/src/main.ts"
    click AppModule "https://github.com/zerocyber/nestjs-template/blob/master/src/app.module.ts"
    click AuthModule "https://github.com/zerocyber/nestjs-template/blob/master/src/auth/auth.module.ts"
    click AuthController "https://github.com/zerocyber/nestjs-template/blob/master/src/auth/auth.controller.ts"
    click AuthService "https://github.com/zerocyber/nestjs-template/blob/master/src/auth/auth.service.ts"
    click SessionSerializer "https://github.com/zerocyber/nestjs-template/blob/master/src/auth/session.serializer.ts"
    click LocalAuthGuard "https://github.com/zerocyber/nestjs-template/blob/master/src/auth/guards/local-auth.guard.ts"
    click QrAuthGuard "https://github.com/zerocyber/nestjs-template/blob/master/src/auth/guards/qr-auth.guard.ts"
    click AuthenticatedGuard "https://github.com/zerocyber/nestjs-template/blob/master/src/auth/guards/authenticated.guard.ts"
    click LocalStrategy "https://github.com/zerocyber/nestjs-template/blob/master/src/auth/strategies/local.strategy.ts"
    click QRStrategy "https://github.com/zerocyber/nestjs-template/blob/master/src/auth/strategies/qr.strategy.ts"
    click UserModule "https://github.com/zerocyber/nestjs-template/blob/master/src/user/user.module.ts"
    click UserController "https://github.com/zerocyber/nestjs-template/blob/master/src/user/user.controller.ts"
    click UserService "https://github.com/zerocyber/nestjs-template/blob/master/src/user/user.service.ts"
    click CreateUserDto "https://github.com/zerocyber/nestjs-template/blob/master/src/user/dto/create-user.dto.ts"
    click UpdateUserDto "https://github.com/zerocyber/nestjs-template/blob/master/src/user/dto/update-user.dto.ts"
    click TodosModule "https://github.com/zerocyber/nestjs-template/blob/master/src/todos/todos.module.ts"
    click TodosController "https://github.com/zerocyber/nestjs-template/blob/master/src/todos/todos.controller.ts"
    click TodosService "https://github.com/zerocyber/nestjs-template/blob/master/src/todos/todos.service.ts"
    click CreateTodoDto "https://github.com/zerocyber/nestjs-template/blob/master/src/todos/dto/create-todo.dto.ts"
    click UpdateTodoDto "https://github.com/zerocyber/nestjs-template/blob/master/src/todos/dto/update-todo.dto.ts"
    click PrismaService "https://github.com/zerocyber/nestjs-template/blob/master/src/prisma.service.ts"
    click PrismaSchema "https://github.com/zerocyber/nestjs-template/blob/master/prisma/schema.prisma"
    click RedisModule "https://github.com/zerocyber/nestjs-template/blob/master/src/common/modules/redis.module.ts"
    click RedisProvider "https://github.com/zerocyber/nestjs-template/blob/master/src/common/providers/redis.provider.ts"
    click LoggingMiddleware "https://github.com/zerocyber/nestjs-template/blob/master/src/common/middlewares/logging.middleware.ts"
    click LoggingInterceptor "https://github.com/zerocyber/nestjs-template/blob/master/src/common/interceptors/logging.interceptor.ts"
    click AppService "https://github.com/zerocyber/nestjs-template/blob/master/src/app.service.ts"
    click UnitTests "https://github.com/zerocyber/nestjs-template/blob/master/src/**/*.spec.ts"
    click E2ETests "https://github.com/zerocyber/nestjs-template/blob/master/test/app.e2e-spec.ts"

    classDef external fill:#ADD8E6,stroke:#000,stroke-width:1px
    classDef module fill:#8FBC8F,stroke:#000,stroke-width:1px
    classDef service fill:#FFA500,stroke:#000,stroke-width:1px
    classDef db fill:#9370DB,stroke:#000,stroke-width:1px,shape:cylinder
    classDef cross fill:#FFD700,stroke:#000,stroke-width:1px
    classDef data fill:#FFE4B5,stroke:#000,stroke-width:1px
    classDef test fill:#D3D3D3,stroke:#000,stroke-dasharray:5 5
```
