พอร์ตและอะแดปเตอร์เพื่อแยกโดเมน
แยกตรรกะทางธุรกิจออกจากเฟรมเวิร์กด้วยการพึ่งพาพอร์ตนามธรรมแทนโครงสร้างพื้นฐานที่เป็นรูปธรรม
พอร์ตและอะแดปเตอร์เพื่อแยกโดเมน เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Isolate the Domain?
In an enterprise NestJS backend, your most valuable code is the business logic: pricing rules, eligibility checks, workflow state machines. This logic should outlive any specific database, message broker, or HTTP framework.
The Ports and Adapters pattern (also called Hexagonal Architecture) achieves this by inverting dependencies. The domain defines abstract ports (interfaces) describing what it needs. Concrete adapters (Postgres, Redis, Stripe) implement those ports and plug in from the outside.
- The domain depends on nothing external.
- Infrastructure depends on the domain, never the reverse.
The Dependency Rule
The core invariant is a one-way dependency arrow: infrastructure → application → domain. Source-code imports may only point inward.
A domain entity must never import from @nestjs/common, TypeORM, or an HTTP client. If it does, you have coupled your rules to a framework's release cycle and made them hard to test in isolation.
Ports live inside the boundary; adapters live outside it. The interface (the port) is owned by the domain, so the domain dictates the contract and the outside world conforms to it.
Defining a Driven Port
A driven port (a.k.a. secondary port) is an outbound dependency the domain needs but does not own. Example: persisting an order. The application layer declares an interface describing exactly what it requires, in domain terms.
Notice this file imports nothing from NestJS or a database driver. It is pure TypeScript describing a capability.
export interface Order {
id: string;
customerId: string;
totalCents: number;
status: 'PENDING' | 'PAID' | 'CANCELLED';
}
// Driven (outbound) port: owned by the application/domain layer.
export interface OrderRepositoryPort {
save(order: Order): Promise<void>;
findById(id: string): Promise<Order | null>;
}A Driving Port: The Use Case
A driving port (primary port) is the entry point into the application, called by the outside world (controllers, CLI, message consumers). It is typically a use-case interface.
The use case orchestrates domain logic and talks to driven ports only through their interfaces. It never knows whether persistence is Postgres or an in-memory map.
export interface PlaceOrderCommand {
orderId: string;
customerId: string;
totalCents: number;
}
// Driving (inbound) port: the application's public contract.
export interface PlaceOrderPort {
execute(cmd: PlaceOrderCommand): Promise<void>;
}Implementing the Use Case
The use case implements the driving port and depends on driven ports by their interface type. Here it validates a business rule, builds a domain entity, and delegates persistence to the port.
This class is framework-agnostic. We add NestJS's @Injectable() only as a thin decoration so the DI container can manage it; the logic itself does not depend on Nest at all.
import { Injectable, Inject } from '@nestjs/common';
import { PlaceOrderPort, PlaceOrderCommand } from './place-order.port';
import { OrderRepositoryPort } from './order-repository.port';
import { ORDER_REPOSITORY } from './tokens';
@Injectable()
export class PlaceOrderUseCase implements PlaceOrderPort {
constructor(
@Inject(ORDER_REPOSITORY)
private readonly orders: OrderRepositoryPort,
) {}
async execute(cmd: PlaceOrderCommand): Promise<void> {
if (cmd.totalCents <= 0) {
throw new Error('Order total must be positive');
}
await this.orders.save({
id: cmd.orderId,
customerId: cmd.customerId,
totalCents: cmd.totalCents,
status: 'PENDING',
});
}
}Injection Tokens for Interfaces
TypeScript interfaces vanish at runtime, so NestJS cannot use them as DI keys directly. The idiom is to define a string or symbol token and bind the port to a concrete adapter in the module.
Always reference the token with @Inject(TOKEN) at injection sites. Symbols avoid accidental string collisions across modules.
export const ORDER_REPOSITORY = Symbol('OrderRepositoryPort');
export const PLACE_ORDER = Symbol('PlaceOrderPort');
// Usage at an injection site:
// constructor(@Inject(ORDER_REPOSITORY) repo: OrderRepositoryPort) {}Writing a Driven Adapter
An adapter implements a driven port using concrete infrastructure. Here a TypeORM adapter satisfies OrderRepositoryPort. It maps between the persistence model and the domain Order, keeping the database schema out of the domain.
The domain never sees OrderEntity or the repository — only the port. Swap to MongoDB tomorrow by writing a new adapter; the use case stays untouched.
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { OrderRepositoryPort, Order } from '../application/order-repository.port';
import { OrderEntity } from './order.entity';
@Injectable()
export class TypeOrmOrderRepository implements OrderRepositoryPort {
constructor(
@InjectRepository(OrderEntity)
private readonly repo: Repository<OrderEntity>,
) {}
async save(order: Order): Promise<void> {
await this.repo.save(this.repo.create(order));
}
async findById(id: string): Promise<Order | null> {
const row = await this.repo.findOne({ where: { id } });
return row ? { ...row } : null;
}
}Wiring Ports to Adapters in a Module
The NestJS module is the composition root where ports meet adapters. Use provide with the token and useClass with the concrete adapter. This is the only place that knows both sides.
Because binding happens here, the entire domain remains ignorant of TypeORM. Tests can supply a different binding without modifying any business code.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { OrderEntity } from './infrastructure/order.entity';
import { TypeOrmOrderRepository } from './infrastructure/typeorm-order.repository';
import { PlaceOrderUseCase } from './application/place-order.usecase';
import { ORDER_REPOSITORY, PLACE_ORDER } from './application/tokens';
@Module({
imports: [TypeOrmModule.forFeature([OrderEntity])],
providers: [
{ provide: ORDER_REPOSITORY, useClass: TypeOrmOrderRepository },
{ provide: PLACE_ORDER, useClass: PlaceOrderUseCase },
],
exports: [PLACE_ORDER],
})
export class OrdersModule {}The Controller is Just Another Adapter
An HTTP controller is a driving adapter: it translates a transport-specific request into a call on the driving port. It holds no business logic — just mapping and delegation.
Replacing REST with gRPC or a Kafka consumer means writing a new driving adapter against the same PlaceOrderPort. The use case never changes.
import { Body, Controller, Inject, Post } from '@nestjs/common';
import { PlaceOrderPort } from '../application/place-order.port';
import { PLACE_ORDER } from '../application/tokens';
@Controller('orders')
export class OrdersController {
constructor(
@Inject(PLACE_ORDER) private readonly placeOrder: PlaceOrderPort,
) {}
@Post()
async create(@Body() body: { orderId: string; customerId: string; totalCents: number }) {
await this.placeOrder.execute(body);
return { status: 'accepted' };
}
}Testing With an In-Memory Adapter
The biggest payoff is testability. Because the use case depends on a port, you test it with a trivial in-memory adapter — no database, no Nest container, no mocking framework.
This snippet is a complete standalone program: it defines the port, a fake adapter, the use case, and runs an assertion. It demonstrates that the domain logic is fully exercisable in isolation.
interface Order {
id: string;
customerId: string;
totalCents: number;
status: 'PENDING' | 'PAID' | 'CANCELLED';
}
interface OrderRepositoryPort {
save(order: Order): Promise<void>;
findById(id: string): Promise<Order | null>;
}
class InMemoryOrderRepo implements OrderRepositoryPort {
private store = new Map<string, Order>();
async save(o: Order) { this.store.set(o.id, o); }
async findById(id: string) { return this.store.get(id) ?? null; }
}
class PlaceOrderUseCase {
constructor(private readonly orders: OrderRepositoryPort) {}
async execute(cmd: { orderId: string; customerId: string; totalCents: number }) {
if (cmd.totalCents <= 0) throw new Error('Order total must be positive');
await this.orders.save({ ...cmd, id: cmd.orderId, status: 'PENDING' });
}
}
async function main() {
const repo = new InMemoryOrderRepo();
const useCase = new PlaceOrderUseCase(repo);
await useCase.execute({ orderId: 'o1', customerId: 'c1', totalCents: 4200 });
const saved = await repo.findById('o1');
console.log(saved?.status === 'PENDING' ? 'PASS' : 'FAIL');
}
main();Anti-Corruption at the Boundary
Adapters double as an anti-corruption layer. External shapes — a Stripe webhook payload, a third-party DTO — must be translated into clean domain types inside the adapter, never leaked inward.
- Keep mapping logic in the adapter, not the use case.
- Never let a vendor's enum or snake_case field reach a domain entity.
- Validate and normalize at the edge so the core trusts its inputs.
This discipline is what keeps the hexagon's interior stable while the messy outside world churns.
import { PaymentPort } from '../application/payment.port';
// Adapter translates a vendor payload into a domain-friendly result.
export class StripePaymentAdapter implements PaymentPort {
async charge(customerId: string, amountCents: number): Promise<{ paid: boolean }> {
const vendorResp = await this.callStripe(customerId, amountCents);
// Map vendor shape -> domain shape (anti-corruption).
return { paid: vendorResp.status === 'succeeded' };
}
private async callStripe(_c: string, _a: number) {
return { status: 'succeeded' as const };
}
}Quick Check
Consider a NestJS use case that must persist data. Where should the persistence interface (the port) be defined, and who implements it?
Recap
You isolated the domain from frameworks using Ports and Adapters:
- Ports are interfaces owned by the domain/application layer — driving (inbound use cases) and driven (outbound dependencies like repositories).
- Adapters live outside the boundary and implement driven ports or call driving ports.
- The dependency rule forces all imports to point inward; the domain depends on nothing external.
- In NestJS, bind ports to adapters in the module using injection tokens (symbols), since interfaces disappear at runtime.
- The payoff: swap infrastructure freely and test business logic in isolation with simple in-memory adapters.
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 20
- บทเรียน
- 76
คำถามที่พบบ่อย
บทเรียน “พอร์ตและอะแดปเตอร์เพื่อแยกโดเมน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “พอร์ตและอะแดปเตอร์เพื่อแยกโดเมน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “พอร์ตและอะแดปเตอร์เพื่อแยกโดเมน”
แยกตรรกะทางธุรกิจออกจากเฟรมเวิร์กด้วยการพึ่งพาพอร์ตนามธรรมแทนโครงสร้างพื้นฐานที่เป็นรูปธรรม คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “พอร์ตและอะแดปเตอร์เพื่อแยกโดเมน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม
ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- พอร์ตและอะแดปเตอร์เพื่อแยกโดเมน
- การลงทะเบียนตัวให้บริการแบบไดนามิกด้วย DiscoveryService
- โมดูลโหลดแบบขี้เกียจและสวิตช์ฟีเจอร์
- จุดขยายด้วย API อ้างอิงโมดูล