百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
N

nestjs-microservice-boilerplate-api

> 后端框架
开源

Nestjs boilerplate 微服务 API | MongoDB CRUD - Postgres CRUD | Docker | Husky | 秘密服务 | HTTP 服务 | 日志服务 | 身份验证 | 授权

393 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

Nestjs boilerplate 微服务 API | MongoDB CRUD - Postgres CRUD | Docker | Husky | 秘密服务 | HTTP 服务 | 日志服务 | 身份验证 | 授权


A Complete, Production-Ready Foundation

This repository is more than an application template: it is a complete, production-oriented microservice foundation. It includes the application, databases, caching, observability, AWS infrastructure, Kubernetes platform, GitOps delivery, and operational workflows needed to run a service in a real environment.

The infrastructure is defined as code with Pulumi and is designed to deploy to AWS using Amazon EKS, Karpenter, Argo CD, and Kubernetes. It also includes secure secret integration, health checks, automated database migrations before application rollouts, autoscaling, persistence, and monitoring components.

This provides a strong production baseline rather than a minimal demo. Before using it in a specific production environment, review the AWS account permissions, network topology, security policies, domains, observability retention, backup strategy, sizing, and environment-specific configuration.

For infrastructure setup and deployment instructions, see the Infrastructure as Code README.

Table of Contents

  • Architecture Overview
  • Architecture Comparison
  • Layer Communication Rules
  • Project Structure
  • Quick Start
  • User Flow
  • Documentation Guides
  • Key Features
  • Tech Stack
  • Contributing
  • License

Architecture Overview

This project implements a pragmatic architecture that combines the best ideas from Clean Architecture, Domain-Driven Design (DDD), and Hexagonal Architecture. Rather than strictly following one pattern, it takes a practical approach: powerful enough for enterprise applications, yet simple enough for any developer to understand and maintain.

The Core Philosophy

The architecture is built around one fundamental principle: protect your business logic. Your domain rules should never depend on frameworks, databases, or external services. If you decide to switch from PostgreSQL to MongoDB, or from Redis to Memcached, your core business logic remains untouched.


Architecture Comparison

Clean Architecture

Clean Architecture organizes code into concentric circles where dependencies point inward. The innermost circle contains business rules, and outer circles contain implementation details.

How we implement it:

  • Entities live in src/core/*/entity — pure business objects
  • Use Cases live in src/core/*/use-cases — application-specific business rules
  • Interfaces live in src/core/*/repository — contracts for external dependencies
  • Frameworks live in src/modules and src/infra — NestJS controllers and database implementations What we simplified:
  • No explicit Interactors or Presenters
  • No input/output boundary classes

Domain-Driven Design (DDD)

DDD focuses on modeling your business domain. It introduces concepts like Entities, Value Objects, Aggregates, and Repositories.

How we implement it:

  • Entities: Objects with identity that persist over time (UserEntity, RoleEntity)
  • Repository Pattern: Abstract interfaces defining data access contracts
  • Use Cases: Encapsulate business operations (similar to Application Services in DDD)
  • Bounded Contexts: Each module represents a bounded context

What we simplified:

  • No Value Objects as separate classes
  • Unified service layer (no Domain/Application Service split)

Service Layer Comparison: DDD vs. This Architecture

In traditional DDD, there are two types of services:

  • Domain Service: Encapsulates domain logic that does not naturally fit within an Entity or Value Object.
  • Application Service: Coordinates use cases, orchestrating entities, repositories, and domain services to fulfill business processes.

In this architecture, both responsibilities are unified into a single component: the UseCase.

  • The UseCase acts as the application service, orchestrating business operations and dependencies.
  • Domain logic that would be placed in a domain service is either implemented within entities or directly in the use case, depending on complexity.

This simplification reduces boilerplate and cognitive overhead, while still maintaining a clear separation between business logic and infrastructure. The result is a leaner, more maintainable service layer without sacrificing the core benefits of DDD.

Hexagonal Architecture (Ports and Adapters)

Hexagonal Architecture separates the application from external concerns through Ports (interfaces) and Adapters (implementations).

How we implement it:

…

Ports (Interfaces):

  • ICatRepository — defines what operations are available
  • IHttpAdapter — defines HTTP client contract
  • ICacheAdapter — defines caching contract

Adapters (Implementations):

  • CatRepository in modules/ — implements ICatRepository with TypeORM/Mongoose
  • HttpService in infra/ — implements IHttpAdapter with Axios
  • RedisService in infra/ — implements ICacheAdapter with Redis

Design Decisions

⚠️ Important Notes About This Architecture

This section explains some deliberate choices that differ from traditional implementations. Understanding these decisions will help you work with the codebase effectively.

Why We Call Interfaces "Adapters"

You may notice that some interfaces in this project use the word "Adapter" (e.g., IHttpAdapter, ICacheAdapter). In traditional Hexagonal Architecture:

  • Port: An interface that defines a contract (what operations are available)
  • Adapter: A concrete implementation that fulfills that contract (how it's done)

The academic distinction:

…

Our simplified approach:

We use "Adapter" in interface names because, conceptually, both are abstractions. The fundamental principle is the same: decouple your core business logic from implementation details. Whether you call the interface a "Port" or "Adapter" doesn't change how the pattern works.

typescript
// Traditional naming
interface IUserRepository {} // Port
class PostgresUserRepository {} // Adapter

// Our naming (simplified)
interface IHttpAdapter {} // Still an abstraction (contract)
class HttpService {} // Still an implementation

Why this simplification?

  1. Reduced cognitive load — One less concept to explain to new developers
  2. Practical focus — The behavior is identical regardless of naming
  3. Consistency — All abstractions follow the same I*Adapter pattern

The key takeaway: if it's an interface, it's a contract. If it's a class implementing that interface, it's the implementation. The names are just labels.


Why We Use Abstract Classes Instead of Interfaces

You may notice that repository contracts use abstract class instead of TypeScript interface:

typescript
// What we use
export abstract class ICatRepository extends IRepository {
  abstract findByBreed(breed: string): Promise
}

// Instead of
export interface ICatRepository extends IRepository {
  findByBreed(breed: string): Promise
}

Why? This is a NestJS/Node.js limitation.

TypeScript interfaces are erased at runtime — they don't exist in the compiled JavaScript. NestJS dependency injection relies on runtime tokens to resolve providers. If we used interfaces, we would need to pass a string token:

typescript
// ❌ With interface — requires string token
@Module({
  providers: [
    {
      provide: 'ICatRepository',  // String token (error-prone, no type safety)
      useClass: CatRepository,
    },
  ],
})

// ✅ With abstract class — class itself is the token
@Module({
  providers: [
    {
      provide: ICatRepository,    // Class reference (type-safe, refactorable)
      useClass: CatRepository,
    },
  ],
})

Benefits of abstract classes:

  1. Type safety — No magic strings, refactoring tools work correctly
  2. Runtime existence — The class exists in compiled JavaScript
  3. Same behavior — Acts as a contract just like an interface
  4. Better DX — IDE autocomplete and "Go to Definition" work properly

The trade-off: Abstract classes can have implementation details (which interfaces cannot). We simply don't use that feature — our abstract classes are pure contracts.


Why the "Middlewares" Folder Contains More Than Middlewares

Yes, we know. The src/middlewares/ folder contains:

  • Middlewares (authentication)
  • Guards (authorization)
  • Interceptors (logging, tracing)
  • Filters (exception handling)

Why didn't we split them?

Honestly? We couldn't find a better name.

We tried:

  • http-pipeline/ — too generic
  • request-handlers/ — not quite right
  • cross-cutting/ — sounds like a buzzword bingo winner
  • stuff-that-runs-before-and-after-your-code/ — accurate but... no

So we stuck with middlewares/ because:

  1. They all operate in the HTTP request/response lifecycle
  2. They're all "things that wrap your controller logic"
  3. Everyone knows where to find them

If you have a better name, PRs are welcome! Until then, just accept that middlewares/ is a "creative interpretation" of the term.


Why Validations Live Inside Use Cases

This is a fundamental difference from many Clean Architecture implementations.

The traditional approach (Clean Architecture):

Controller → Validates Input → Use Case → Business Logic

In traditional Clean Architecture, input validation happens in the Controller or a dedicated Validation layer before reaching the Use Case. The Use Case assumes it receives valid data.

Our approach:

Controller → Use Case (Validates + Business Logic)

We validate inputs inside the Use Case using Zod schemas.

Why we made this choice:

  1. Testability

    When you test a Use Case, you should test the complete behavior — including validation. It's unacceptable to have a Use Case that passes tests but fails in production because validation was bypassed.

    typescript
    // Our tests validate the complete use case behavior
    it('should throw validation error for invalid email', async () => {
      const input = { email: 'invalid-email', name: 'John' }
      await expect(useCase.execute(input)).rejects.toThrow(ValidationException)
    })
  2. Use Case Integrity

    A Use Case is a complete unit of business logic. If CreateUserUseCase requires a valid email, that validation IS part of the use case — not something external to it.

  3. Self-Documenting Code

    Looking at a Use Case, you immediately see what inputs it expects and how they're validated. No need to hunt through multiple layers.

  4. Reduced Duplication

    If multiple controllers call the same Use Case, validations are automatically applied. No risk of one controller forgetting to validate.

Comparison with other approaches:

Approach Validation Location Pros Cons
Traditional Clean Controller/Validator layer Thin use cases Validation can be bypassed, harder to test
DDD Domain entities (Value Objects) Rich domain model Complex, verbose
Our Approach Inside Use Case Complete testability, self-contained See trade-offs below

The trade-off:

If you need to consume a Use Case from multiple entry points with different validation rules, the Use Case validations might be too restrictive.

Solution: For those cases, move specific validations to the Application layer (Control

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScriptauthenticationauthorizationboilerplateclean-arch

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架