Token导航 LogoToken导航TokenDH.com
待分类权限需确认github未标认证来源可访问许可证需确认审计提醒

hexagonal-architecture六边形架构

Agent Skill

hexagonal-architecture 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

279

周安装

12

GitHub Stars

643

下载量

98
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:hexagonal-architecture(六边形架构)
来源仓库:https://github.com/citypaul/.dotfiles
仓库路径:skills/hexagonal-architecture
安装命令:
npx skills add https://github.com/citypaul/.dotfiles --skill hexagonal-architecture
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/citypaul/.dotfiles --skill hexagonal-architecture

简介

用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,辅助整理项目状态与变更事项。

  • 适用于 Codex、Claude、Cursor、Gemini CLI 中需要围绕代码协作进行梳理的场景。
  • 可结合来源仓库和原始 README 进一步核验具体用法和功能范围。
  • 安装前建议确认权限范围、维护状态及是否会触发联网或文件读写操作。
  • hexagonal-architecture 属于待分类类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

name
hexagonal-architecture
description
Hexagonal (ports and adapters) architecture patterns for TypeScript. Use when implementing ports, adapters, dependency inversion, or domain isolation. Only applies to projects that explicitly use hexagonal architecture. Do NOT use for projects without ports/adapters structure.

Hexagonal Architecture (Ports & Adapters)

This skill applies only to projects that have opted in to hexagonal architecture. Do not apply these patterns to projects that use a different architecture. For introducing hex arch into an existing codebase incrementally, see resources/incremental-adoption.md.

For domain modeling (entities, value objects, aggregates, ubiquitous language), load the domain-driven-design skill. Hex arch and DDD are complementary but independent — hex arch provides structural isolation (how the outside connects), DDD provides the domain model (what lives in the center). A project may use one without the other.

Deep-dive resources are in the resources/ directory. Load them on demand:

ResourceLoad when...
worked-example.mdNeed a full feature traced through every layer with tests and file map
testing-hex-arch.mdWriting tests, creating fakes, setting up createTestDb, swappability test
cqrs-lite.mdReads need to JOIN across aggregates, separating read/write paths
cross-cutting-concerns.mdPlacing auth, logging, transactions, or error formatting
incremental-adoption.mdIntroducing hex arch into an existing codebase

For authoritative sources, see ../REFERENCES.md.


Core Concept

Business logic lives in the center. External systems connect through ports (interfaces) and adapters (implementations). Dependencies point inward — the domain never knows about the outside world.

         Driving (left)                    Driven (right)
    ┌──────────────────┐            ┌──────────────────┐
    │  Route handlers  │            │  Repositories    │
    │  CLI commands    │──────┐┌────│  API clients     │
    │  Event listeners │      ││    │  Email services  │
    └──────────────────┘      ││    └──────────────────┘
         call into ──────►  ┌────┐  ◄────── implement
                            │    │
                            │ DO │
                            │ MA │
                            │ IN │
                            │    │
         call into ──────►  └────┘  ◄────── implement
    ┌──────────────────┐      ││    ┌──────────────────┐
    │  Cron triggers   │──────┘└────│  File storage    │
    │  Message queues  │            │  Payment gateway │
    └──────────────────┘            └──────────────────┘

Driving adapters (left): initiate actions on the application. They *call* use cases. Driven adapters (right): the application reaches out to them. They *implement* port interfaces.

This asymmetry is fundamental. Driving adapters depend on use case interfaces. Driven adapters implement repository/gateway interfaces defined by the domain.


Ports = Interfaces

Ports define contracts between layers. They are always interface types (behavior contracts, not data shapes).

// Driven port — defined in domain, implemented by adapters
interface UserRepository {
  readonly findById: (id: UserId) => Promise<User | undefined>;
  readonly save: (user: User) => Promise<void>;
}

// Driven port — defined in domain, implemented by adapters
interface PaymentGateway {
  readonly charge: (amount: Money, paymentInfo: PaymentInfo) => Promise<ChargeResult>;
}

// Driven port — event publishing (outbound to message brokers)
interface OrderEventPublisher {
  readonly publish: (event: OrderEvent) => Promise<void>;
}

Port design principles:

  • Name ports by business purpose, not technology (UserRepository, not DatabasePort)
  • Keep ports focused — one per aggregate or capability, not one god port
  • Port methods use domain types, never infrastructure types (no SqlRow, no HttpResponse)
  • Creation param schemas co-locate with the repository port they describe

Adapters = Implementations

Adapters implement ports for specific technologies. A good adapter is simple — it translates between the port's domain types and the technology's native types. No business logic.

// Driven adapter — implements the repository port using Drizzle/D1
const createDrizzleUserRepository = (db: D1Database): UserRepository => ({
  findById: async (id) => {
    const row = await db.select().from(users).where(eq(users.id, id)).get();
    return row ? toUser(row) : undefined;
  },
  save: async (user) => {
    await db.insert(users).values(toRow(user)).onConflictDoUpdate({ ... });
  },
});

// Driven adapter — implements the same port for tests
const createFakeUserRepository = (initial: readonly User[] = []): UserRepository => {
  const store = new Map(initial.map(u => [u.id, u]));
  return {
    findById: async (id) => store.get(id),
    save: async (user) => { store.set(user.id, user); },
  };
};

Adapter error handling: Infrastructure errors (connection lost, timeout, constraint violation) should either propagate as exceptions to a top-level handler or be translated into domain-appropriate results at the adapter boundary. The domain never catches infrastructure errors — it doesn't know infrastructure exists.

// Driven adapter: translate expected infrastructure errors into domain-specific errors
const createDrizzleUserRepository = (db: Database): UserRepository => ({
  save: async (user) => {
    try {
      await db.insert(users).values(toRow(user)).onConflictDoUpdate({ ... });
    } catch (e) {
      if (isUniqueConstraintError(e)) throw new UserAlreadyExistsError(user.id);
      throw e; // unexpected errors (connection lost, disk full) propagate
    }
  },
});

Expected constraint violations become domain-specific errors (caught by the use case or driving adapter). Unexpected infrastructure errors propagate to the top-level handler.

Key principle: If swapping an adapter requires changing domain code, the boundary is wrong.


Reads vs Writes (CQRS-lite)

Not all reads need to go through repositories. The repository pattern enforces aggregate boundaries — essential for writes, but reads often need to JOIN across aggregates for display.

OperationPatternExample
WriteRepository (one aggregate)userRepo.save(user)
Read (single aggregate)RepositoryuserRepo.findById(id)
Read (cross-aggregate, display)Query function (JOINs freely)getEventDetail(db, eventId)

Query functions are driven adapters too — they live in the adapter layer (e.g., db/queries/) and return read-optimized DTOs. They bypass the repository pattern intentionally.

// Query function — JOINs across aggregates for display
// Lives in db/queries/, NOT in domain/
const getParticipantEventView = async (db: Database, eventId: string) => {
  return db.select({ ... })
    .from(events)
    .innerJoin(occasions, ...)
    .leftJoin(giftClaims, ...)
    .where(eq(events.id, eventId))
    .all();
};

Domain-layer pure functions can transform query results into display types — these encode business rules about what data means (e.g., "is this item claimed by the current user?"). The query fetches; the domain function interprets.

For detailed CQRS-lite guidance, see resources/cqrs-lite.md.


Dependency Injection

Inject all dependencies via function parameters. No DI container needed. The driving adapter gathers impure dependencies, passes them to the use case, and acts on the result — Seemann's "impureim sandwich" (impure/pure/impure).

// WRONG — creates dependencies internally (untestable, tightly coupled)
const createOrder = async (order: NewOrder) => {
  const repo = new DrizzleOrderRepo(getDb());          // hardcoded
  const gateway = new StripeGateway(process.env.KEY);   // hardcoded
  // ...
};

// RIGHT — dependencies as parameters (testable, swappable)
const createOrder = async (
  repo: OrderRepository,
  gateway: PaymentGateway,
  order: NewOrder,
): Promise<OrderResult> => {
  const charge = await gateway.charge(order.total, order.payment);
  if (!charge.success) return { success: false, reason: charge.error };
  const saved = await repo.save({ ...order, chargeId: charge.id });
  return { success: true, order: saved };
};

Composition root: Wiring happens at the application entry point — where adapters are created from environment/config and injected into use cases. This is the only place that knows about concrete implementations.

// Route handler = composition root + driving adapter
export async function POST(request: Request) {
  const { env } = getCloudflareContext();
  const db = createDb(env.DB);

  // Wire adapters
  const repo = createDrizzleOrderRepository(db);
  const gateway = createStripeGateway(env.STRIPE_KEY);

  // Call use case
  const body = CreateOrderSchema.parse(await request.json());
  const result = await createOrder(repo, gateway, body);
  return NextResponse.json(result);
}

The route handler is thin glue: parse input → wire adapters → call use case → return response. No business logic.

Non-HTTP driving adapters follow the same pattern — parse, wire, delegate:

// Queue consumer = driving adapter (same structure as route handler)
const handlePledgeMessage = async (message: SQSMessage, env: Env) => {
  const db = createDb(env.DB);
  const occasionRepo = createDrizzleOccasionRepository(db);
  const contributorRepo = createDrizzleContributorRepository(db);

  const dto = PledgeSchema.parse(JSON.parse(message.body));
  await handlePledge(occasionRepo, contributorRepo, dto);
};

The use case doesn't know or care whether it was triggered by an HTTP request, a queue message, a cron job, or a CLI command. Every driving adapter is thin glue.

Naming: Use cases are named after the business operation — createOrder, placeOrder, handlePledge. Never createOrderUseCase or PlaceOrderHandler. Pattern suffixes are technical jargon, not domain language. You can tell a use case from a domain function by its signature — use cases take ports (repositories, gateways) as parameters; domain functions take only domain types.


File Organization

LayerLocationContainsTests
Domainsrc/domain/Business logic (pure functions), types, port interfaces, use cases (orchestration)Unit + use case tests (fakes)
Adapters (driven)src/db/, src/infrastructure/Repository impls, API clients, query functionsIntegration tests (real DB/MSW)
Adapters (driving)src/app/Route handlers, event listenersE2E tests (Playwright)
Wiringsrc/lib/, src/context.tsAdapter factories, config, compositionCovered by E2E

Key rules:

  • Domain has zero external dependencies (no framework, database, or HTTP imports)
  • Port interfaces live in domain alongside the entity they serve
  • Schemas co-locate with their entity in domain
  • Adapters import from domain, never the reverse
  • Route handlers are thin — parse, wire, delegate, respond

Testing Strategy

Hex arch's primary benefit is testability. The primary test boundary is the use case — call it with driven ports replaced by in-memory fakes (not mocks). This proves the feature works as a whole.

PriorityBoundaryWhat it proves
PrimaryUse case (faked driven ports)Feature works end-to-end within the hexagon
ComplementDomain pure functionsComplex business rules in isolation
SecondaryDriven adapters (real DB/MSW)Adapter translates correctly
VerificationE2E (full stack)User experience works

Fakes over mocks: Fakes implement the real interface and maintain state. Mocks verify call sequences and break on refactoring. See resources/testing-hex-arch.md for detailed patterns.

For a complete worked example showing one feature traced through every layer (glossary → types → domain → use case → adapters → tests → file locations), see resources/worked-example.md.


Cross-Cutting Concerns

ConcernWhereWhy
Authentication (who are you?)Driving adapterProtocol-specific (JWT, session, API key)
Authorization (are you allowed?)DomainBusiness rule about permissions
LoggingAdapters (both sides)Side effect, not business logic
TransactionsAdapter / composition rootInfrastructure concern, domain unaware
Error formattingDriving adapterTranslates domain results to HTTP/gRPC

The domain never imports a logger, catches HTTP errors, or manages transactions. It returns results; adapters handle the rest. See resources/cross-cutting-concerns.md for detailed patterns.


Anti-Patterns

Domain Depending on Infrastructure

The most common hex arch violation. Domain code imports from frameworks, databases, or external services.

// ❌ Domain imports Drizzle
import { eq } from 'drizzle-orm';
export const findActiveUsers = async (db) => db.select()...

// ✅ Domain defines the contract; adapter implements it
interface UserRepository {
  readonly findActive: () => Promise<readonly User[]>;
}

Business Logic in Adapters

Route handlers or repositories contain business rules instead of delegating to domain.

// ❌ Business rule in route handler
export async function POST(request: Request) {
  const order = await orderRepo.findById(id);
  if (order.total > 1000) { await requireManagerApproval(order); } // business rule!
  ...
}

// ✅ Business rule in domain
const placeOrder = (order: Order): PlaceOrderResult => {
  if (order.total > 1000) return { success: false, reason: 'requires-approval' };
  ...
};

Bypass Adapters

Route handler accesses the database directly instead of going through a port.

// ❌ Route handler hits DB directly
export async function GET(request: Request) {
  const users = await db.select().from(users).where(eq(users.active, true));
  ...
}

// ✅ Route handler calls use case, which uses a port
const result = await getActiveUsers(userRepo);

Port Proliferation

Creating a port for every tiny abstraction. Ports should represent meaningful boundaries — one per aggregate (repositories) or per external capability (payment, email, auth).

Technology-Shaped Ports

Port methods that expose technology details. Port methods should use domain language.

// ❌ Technology leaks into port
interface UserRepository {
  readonly findBySqlQuery: (sql: string) => Promise<User[]>;
  readonly getFromRedisCache: (key: string) => Promise<User>;
}

// ✅ Business language
interface UserRepository {
  readonly findActive: () => Promise<readonly User[]>;
  readonly findById: (id: UserId) => Promise<User | undefined>;
}

Checklist

  • [ ] Domain logic has zero framework/infrastructure dependencies
  • [ ] All external boundaries use ports (interfaces)
  • [ ] Driving adapters (routes) are thin — parse, wire, delegate, respond
  • [ ] Driven adapters (repos) implement ports, contain no business logic
  • [ ] Dependencies injected via parameters, never created internally
  • [ ] Port interfaces live in domain, named by business purpose
  • [ ] Schemas defined in domain, not duplicated in adapters
  • [ ] Reads that JOIN across aggregates use query functions (CQRS-lite)
  • [ ] Each layer has behavioral tests at the appropriate level
  • [ ] Swapping any adapter requires zero domain code changes
  • [ ] Cross-cutting concerns (auth, logging, transactions) live in adapters, not domain
  • [ ] Domain returns result types for expected outcomes, never throws for business rules

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.49%
按下载量换算33

Claude

30.5%
按下载量换算30

Cursor

17.39%
按下载量换算17

Gemini CLI

8.94%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

权限需确认

当前来源未能明确判断权限范围,默认进入异常复核队列。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills