/engineering-paved-path:onion-architecturefrom engineering-paved-path
Onion-architecture rules for a TypeScript backend (written for Fastify + Drizzle/Postgres, applicable to any Node HTTP framework and ORM): which ring a file belongs to (domain, application, infrastructure, presentation), which way imports may point, and where ports, services, repositories, routes, mappers, adapters and DI wiring live; optionally enforced in CI with dependency-cruiser. Use whenever creating, moving, splitting or reviewing backend code — a new feature module, a route that queries the database, a service that keeps growing, 'where should this live', adding an SDK/adapter/port, wiring the DI container, transactions, or a structure-focused PR review — even if the user never says 'architecture' or 'onion'. Not for Fastify API usage (fastify-best-practices), Drizzle query syntax (drizzle-orm-patterns), table design (postgresql-table-design), schemas (zod), or vulnerabilities (security).
Ships in engineering-paved-path. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
How a TypeScript backend (examples: Fastify 5, Drizzle + Postgres) is organized: which ring each file belongs to, which way dependencies point, and where each kind of code lives.
The principles are general. The paths below use a neutral sample application — a small
commerce API with feature modules such as orders, customers, catalog, payments and
notifications under src/modules/<name>/, shared contracts in src/shared/contracts/, adapters in
src/adapters/ and a DI container in src/platform/container.ts. Map them onto your project's
folders before applying a rule — see project-mapping.
Version 2.0.0 — sources, rationale and history are in README.md.
Link instead of restating rules another skill owns; two copies drift apart.
| Question | Owner |
|---|---|
| Which ring does this file belong to? What may it import? Where do ports / services / repositories / routes / adapters live? Who wires them? Who owns the transaction? | this skill |
| Fastify API: hooks, plugin options, serialization, logging, deployment | fastify-best-practices |
| Drizzle query / relation / migration syntax | drizzle-orm-patterns |
| Table and index design | postgresql-table-design |
| Zod schema technique | zod |
| Authz, injection, secrets handling | security |
| Type-level TypeScript | typescript-expert |
| How your app is wired end to end | your project's architecture doc / agent guide, if it has one |
Precedence when guidance conflicts: your project's own written architecture rules > this skill > generic advice.
Dependencies point inward only. The inner ring never names anything from an outer one.
| Ring | What it is | Files in the sample app |
|---|---|---|
| 1 Domain | Vocabulary and pure rules. No I/O, no framework. | shared contracts (src/shared/contracts/) · modules/<m>/domain/ · constants.ts · types.ts · any pure engine/library the app consumes |
| 2 Application | Use cases and the ports they need. | modules/<m>/service.ts · modules/<m>/ports.ts · cross-module infra ports in src/shared/ports.ts |
| 3 Infrastructure | Implements ports with real tools. | modules/<m>/repository.ts (Drizzle) · src/db/** · src/adapters/** (payment gateway, mailer, object storage, search, LLM SDKs) · platform/jobs.ts, platform/events.ts |
| 4 Presentation & composition | HTTP in, wiring. | modules/<m>/routes.ts · app.ts · platform/container.ts · modules/index.ts |
Test for any file: could it run without the HTTP framework, the database and the network? Yes → rings 1–2. No → ring 3 or 4, and something inner must own the interface it implements or calls.
chargeOrder), not the tool's API (stripe.paymentIntents.create).FastifyRequest, Drizzle rows/sql, and
vendor SDK types never enter rings 1–2. Cross a boundary with plain data or a shared contract.Container (that is a service locator: it hides what the use case depends on).new SomeAdapter() / new SomeRepository(db) appear in
the composition root (platform/container.ts) and tests, nowhere else.index.ts (rule 10) and
ports.ts — types.ts only where rule 11 publishes it. Slice by feature, layer inside each slice
(sliced onion).orders → orders, payments → payments, customers →
customers). Another module that must change that data calls the owner's port, exposed through the
owner's index.ts/ports.ts and wired in the Container. Read-only joins onto a foreign table
inside your own repository are fine. Import linters cannot see this (every repository imports
the schema), so reviewers must check it by hand — see
drizzle-persistence-layer § Table ownership.jobs.enqueue, an event stream, or sleep/retry. The
violation is usually not on the line that opens the transaction — it hides two or three calls
deeper (a private method, a module helper class, an injected collaborator, a callback). Find it with
the transaction trace in
drizzle-persistence-layer § Transaction trace,
and report the whole call chain.index.ts is allowed only for
what may cross a module boundary: contract types, ports (interfaces), constants and
pure domain/ functions. A class or function that does I/O or knows rows — another module's
*Service, *Repository, mapper (toXDto, toXRecord), routes plugin, helpers — is still an
internal import when it arrives via ../<other>/index.js. Depend on a port declared in your
ports.ts (or the other module's ports.ts) and let the Container pass the implementation.
Import linters usually whitelist every index.ts, so they cannot see this — check it by hand
(layers-and-dependency-rule § Barrels).types.ts is private. It holds that module's request/response zod schemas,
job payloads and internal input shapes; importing it ties your routes, ports or domain to another
module's HTTP surface and storage inputs. A type that must cross modules lives in the shared
contracts or in the owner's ports.ts. If a module deliberately publishes its types.ts (e.g. a
facade interface and its result types — see
ports-and-adapters-for-tools § The facade pattern),
record it as a published exception in your project mapping; keep that list short and explicit.
Anything else imported from ../<other>/types.js (directly or re-exported through its index.ts)
is a violation, even import type. Check by hand:
rg -n "from '\.\./(\.\./)?[a-z-]+/types\.js'" src/modules/<m>.| You have… | It goes in… |
|---|---|
Route path, zod params/body, status code | routes.ts (thin: schema → request context → service → contract) |
| Multi-step operation, a decision, calls to several ports | service.ts |
| Repository interface | ports.ts (application ring) |
Drizzle query, sql, db/schema, row ↔ contract mapping | repository.ts (+ mappers.ts beside it); returns contract types, never rows |
| Pure rule (derive status, compute a total, group, parse) | domain/<purpose>.ts — no I/O, unit-tested alone |
| Literals, option lists | constants.ts |
| Zod schema / type used only by this module (request body, query, response shape) | types.ts — zod is allowed in ring 1; derive types with z.infer. Private — other modules never import it (rule 11) |
A type or schema you found in another module's types.ts and want to reuse | copy the shape into your types.ts, or move it to the shared contracts / the owner's ports.ts with its owner — never import it (unless it is a recorded published exception) |
| Contract the frontend (or another service) also needs | the shared contracts package — edit at its source. If that source lives outside this repository, plan the change with its owner; until it lands keep the schema in types.ts |
| New table / column | db/schema/<name>.ts + barrel export (+ the schema object your ORM setup uses) + a generated migration (e.g. drizzle-kit generate --name <name>); never edit an applied migration |
| External system (payment provider, email, object storage, search, LLM, git, …) | port → adapter in src/adapters/<tool>/ → fake in src/adapters/mocks.ts → wired in Container |
| Secret or token | a SecretsProvider port (or your config/secrets layer) only — never read ad hoc from env/db inside a service |
| Background work | handler registered on the job runner from the service; payload type in types.ts |
| Tenant / user scope | resolved in the route (e.g. getRequestContext(req)); pass tenantId to the service as a plain argument |
| Failure | throw AppError / NotFoundError from the service; the global error handler maps it |
| Something another module already does (its service, repository, mapper) | a port in your ports.ts shaped for your use case, implemented by the Container (adapting the other module's service/repository there) — never import { XService | XRepository | toXDto } from '../x/index.js' |
Change rows of a table another module owns (orders, payments, customers, …) | the owner's repository, reached through the owner's port (index.ts/ports.ts, wired in Container) — never insert/update/delete on it from your repository |
| External call or job that belongs to an atomic use case | outside the transaction: fetch/compute before tx.run, call the network / jobs.enqueue / events after commit; if the side effect must be atomic with the writes, write an intent (outbox) row inside the transaction and let a job perform it |
| Atomic multi-write | the service opens the transaction (see drizzle-persistence-layer) |
| Test | per ring — testing-by-layer |
Details: layers-and-dependency-rule, ports-and-adapters-for-tools.
src/modules/<name>/
routes.ts # 4 HTTP plugin/router; the only file that knows HTTP
service.ts # 2 use cases; constructor(deps: <Name>Deps)
ports.ts # 2 <Name>Repository + any port only this module needs
repository.ts # 3 ORM implementation of the ports
mappers.ts # 3 row → contract; may import row TYPES, not the ORM
domain/ # 1 optional: pure rules
constants.ts # 1
types.ts # 1 module-local zod schemas + inferred types, payloads
index.ts # public facade for OTHER modules, only if they need one
Create files on demand. If your project already uses other names (*.controller.ts,
*.handler.ts, *.dao.ts), keep them and map each onto a ring once, in your project mapping; the
rules are about rings and direction, not file names (but import linters match by name, so be
consistent).
New module — constants.ts + types.ts (zod contracts) → domain/ rules → ports.ts →
service.ts (constructor deps) → table in db/schema/ + generated migration → mappers.ts +
repository.ts → routes.ts → register in modules/index.ts → wire in Container
(getter + a <name>Repo override key) → tests per ring → import-rule check (below).
Touching an existing module — do not make it worse and do not grow the baseline. Fix the
violations in the code you are changing when it is cheap (move the query into the repository;
pass a narrow dep instead of Container); otherwise leave a one-line note. Do not start a
module-wide refactor inside an unrelated change. Record known drift and a migration order in your
project mapping (project-mapping).
Reviewing — read top to bottom and ask the checklist; run the transaction trace for every
transaction in the change; report each violation with the target location ("move this query to
OrderRepository.listByCustomer"), not just "wrong layer".
The rules that are about imports can be checked mechanically. One option is dependency-cruiser: forbid rules in a config file, existing drift frozen in a baseline file, a new violation fails CI.
npx depcruise src --config .dependency-cruiser.cjs --ignore-known
When you fix a baselined violation, regenerate the baseline so it shrinks. Never add a violation to the baseline to make CI pass. A generic rule set and the procedure are in enforcement. Rules 8–11 are not import-shaped and stay review-only.
routes.ts has no ORM, no SQL, no business rule; it calls a service.Container; no FastifyRequest (or other framework type) inside.repository* imports the ORM library, db/schema or row types (only
mappers.ts may import row types, never the ORM).src/adapters/.types.ts (direct or via its barrel) except a recorded
published exception (rule 11).from '../<other>/index.js' (and ../<other>') imports only types, ports, constants or pure
domain functions — no *Service, *Repository, mapper or routes symbol, even as import type
used for a constructor dependency.insert/update/delete targets a table this module owns; writes to another module's
table go through the owner's port (grep the diff for .insert(t. / .update(t. / .delete(t.).transaction( / tx.run( in the change: every call inside the
callback followed to a leaf; no port to an external system, no jobs.enqueue, no event emit, no
sleep/retry is reachable (report violations with the full chain a → b → port.method).| File | Read it when |
|---|---|
| references/layers-and-dependency-rule.md | Deciding a file's ring; the import matrix; barrels; borderline cases |
| references/fastify-presentation-layer.md | Writing or slimming a routes.ts; plugin scope, decorators, error mapping, streaming |
| references/drizzle-persistence-layer.md | Repositories, row ↔ contract mapping, table ownership, transactions + transaction trace, raw SQL, migrations |
| references/ports-and-adapters-for-tools.md | Adding or replacing a payment / email / storage / search / LLM / git / job-queue integration |
| references/composition-root-and-di.md | Replacing Container params, container getters, overrides |
| references/testing-by-layer.md | Choosing the right kind of test for the code you wrote |
| references/enforcement.md | Setting up import rules; a rule fired; updating the baseline; adding a rule or an exception |
| references/project-mapping.md | Mapping the rings onto your folders; recording drift, published exceptions, settled decisions |
README.md (opens in a new tab)references/composition-root-and-di.md (opens in a new tab)references/drizzle-persistence-layer.md (opens in a new tab)references/enforcement.md (opens in a new tab)references/fastify-presentation-layer.md (opens in a new tab)references/layers-and-dependency-rule.md (opens in a new tab)references/ports-and-adapters-for-tools.md (opens in a new tab)references/project-mapping.md (opens in a new tab)references/testing-by-layer.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub humen-dev/dev-digest-ai-marketplace --plugin engineering-paved-path12 skills in this plugin
/drizzle-orm-patternsProvides comprehensive Drizzle ORM patterns for schema definition, CRUD operations, relations, queries, transactions, and migrations. Proactively use for any Drizzle ORM development including defining database schemas, writing type-safe queries, implementing relations, managing transactions, and setting up migrations with Drizzle Kit. Supports PostgreSQL, MySQL, SQLite, MSSQL, and CockroachDB./fastify-best-practicesGuides development of Fastify Node.js backend servers and REST APIs using TypeScript or JavaScript. Use when building, configuring, or debugging a Fastify application — including defining routes, implementing plugins, setting up JSON Schema validation, handling errors, optimising performance, managing authentication, configuring CORS and security headers, integrating databases, working with WebSockets, and deploying to production. Covers the full Fastify request lifecycle (hooks, serialization, logging with Pino) and TypeScript integration via strip types. Trigger terms: Fastify, Node.js server, REST API, API routes, backend framework, fastify.config, server.ts, app.ts./frontend-ui-architectureArchitecture and code-organization rules for a React / Next.js (App Router) frontend: where components, hooks, constants, helpers, styles, types, tests and business logic live, how to split a component, which layers may import which, and where the server/client boundary goes. Use whenever creating, moving, splitting or reviewing UI code — a new page, feature or _components/<Name> folder, a component that keeps growing, 'where should this constant/helper/hook/type go', restructuring, or a structure-focused PR review — even if the user never says 'architecture'. Not for effects/memoization/keys/a11y (react-best-practices), Next.js APIs (next-best-practices), test technique (react-testing-library), or Zod.Other plugins' skills for the same job