stack-nestjs
Skill0 starsChanged 5 months agoApache-2.0View on GitHub
NestJS implementation patterns for agents working in projects whose docs/TECH_STACK.md lists nestjs. Load when implementing, testing, or reviewing code on this stack.
- Reads credentials
In this repository17 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- flow-adoptionSkill
- flow-legacy-migrationSkill
- stack-awsSkill
- stack-azureSkill
- stack-design-systemSkill
- stack-gcpSkill
- stack-javaSkill
- stack-kafkaSkill
- stack-mongodbSkill
- stack-natsSkill
- stack-nextjs-reactSkill
- stack-nxSkill
- stack-playwrightSkill
- stack-postgresqlSkill
- stack-quarkusSkill
- stack-react-nativeSkill
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 3 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 57
No business logic in controllers/resolvers.
- Distinctive: line 75
If GraphQL: relation resolvers use a DataLoader from day one.
- Distinctive: line 77
Every controller/resolver failure path logs a structured error with correlation ID.
- Very specific: line 121
All rows must pass before commit per .claude/rules/LIVE_VALIDATION.md.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Stack: NestJS
The transport layer is a PER-PROJECT choice — GraphQL code-first, ts-rest, or plain REST. Read the host's docs/ARCHITECTURE.md before assuming any of them. Everything below the presentation layer is transport-agnostic.
When this applies
Detection markers (any of):
docs/TECH_STACK.md## Detected stackslistsnestjs- Dependencies:
@nestjs/core,@nestjs/common; optionally@nestjs/graphql,@ts-rest/nest,@nestjs/mongoose - Files:
nest-cli.json, amain.tswithNestFactory.create,*.module.tsfiles
Implementation patterns
These are the patterns this stack commonly uses (extracted from a proven hexagonal NestJS lineage). Where the host's docs/ARCHITECTURE.md declares different conventions, the host docs win.
Hexagonal layout — layer folders inside the module, role carried by file suffix
src/modules/<context>/ # modular monolith; a single-context service uses src/<context>/
├── domain/ # PURE core — entity, ports (abstract classes), use-case services, RuleSets (+ their *.spec.ts)
│ ├── <entity>.ts
│ ├── <port>.ts # <entity>.repository.ts · event-bus.ts · clock.ts
│ ├── <use-case>.service.ts
│ └── <use-case>.rules.ts
├── adapters/ # port implementations, one per binding: <port>.<tech>.ts (.prisma.ts, .mongoose.ts, .nats.ts …)
├── presentation/ # <use-case>.{resolver,controller,input,model}.ts
└── <context>.module.ts # wiring — the ONLY file that names concrete adapter classes- Layer folders are the DEFAULT, not an option. A flat module folder buries review signal once it passes ~10 files; the file suffix still names the role and MUST agree with the folder it sits in.
- PURE core (
domain/) imports nothing outward. Adapters → domain. Presentation → domain. Never the reverse. - The inward arrow is lint-enforced (
no-restricted-imports/@nx/enforce-module-boundaries); never disable that rule — it is load-bearing in CI. - In a modular monolith,
index.tsat the module root is the module's public API — the only legal cross-module import surface (.claude/docs/DEFAULT_TARGET_ARCHITECTURE.md§2). - Shared app infra never lives inside a domain module. App-owned connection handles — broker connection, custom transport clients, the R-PAT-03 bare-client fallback pool — live in
src/infrastructure/, provided/exported byinfrastructure.module.ts; module adapters inject the handle. A pool or connection provider sitting inside a domain module is a review BLOCKER.
DON'T
// booking.service.ts — a PURE-core suffix
import { PrismaClient } from '@prisma/client' // core importing infra = arrow invertedThree-phase orchestration (every use-case)
async execute(input: Input): Promise<Result> {
const ctx = await this.gatherFacts(input) // 1. ALL I/O happens here
const verdict = rules.evaluate(ctx) // 2. pure — no I/O inside rules
if (!verdict.ok) throw new RuleViolation(verdict.violations)
const written = await this.repo.create(/*...*/)
await this.events.publish(/*...*/) // 3. effects, post-commit
return written
}- RuleSet purity: rules are pure predicates over
ctx— no I/O, no closures over ambient state. Default mode collect-all (report every violated rule, structured: which rule, why); fail-fast only when later rules are meaningless after an earlier failure. - No business logic in controllers/resolvers. No I/O in rules. Gathering after evaluating is a phase violation.
DI boundaries
- The repository contract is an abstract class — the contract IS the DI token. No string/symbol tokens.
- Module wiring:
{ provide: EntityRepository, useClass: PrismaEntityRepository }. - Map driver/transport errors to typed domain errors at the adapter boundary (e.g. unique violation →
IdempotencyReplay, exclusion conflict →SlotTaken). Domain code never inspects driver error codes.
Persistence — Nest's first-party data module, not the bare driver (R-PAT-03)
- The adapter is built on Nest's own integration module for the store, never the raw driver wired by hand: MongoDB →
@nestjs/mongoose(MongooseModule.forFeature,@InjectModel), not baremongoose/mongodb; SQL →@nestjs/typeorm(or the Nest Prisma module pattern the host'sdocs/ARCHITECTURE.mddeclares), not a hand-constructedDataSource/pgpool. The module owns connection lifecycle, pooling, transaction binding, and DI — bypassing it re-implements that surface and forfeitsTest.createTestingModulewiring. - Inject the module-provided handle (
@InjectModel(X.name), the injected repository/DataSource) into the adapter only — never into a service or the domain (the abstract repository contract is still the only thing the core sees). - Fallback to a bare client is legitimate only when Nest ships no module for the store; then the pooled client is provided by
src/infrastructure/(infrastructure.module.ts) and injected into the adapter — still behind the port, and nowhere else.
Validation at the edges (Zod)
- Validate ALL external input at the presentation boundary with Zod schemas; inside the boundary, types are trusted.
- In a monorepo, shared Zod input schemas live in the domain's contract lib so consumers and the server derive from one source.
Cross-cutting
- Auth/permissions via guards (
CanActivate) at the presentation layer — never middleware. - If GraphQL: relation resolvers use a DataLoader from day one.
- Idempotency: any write the spec marks idempotent accepts an idempotency key and replays correctly.
- Every controller/resolver failure path logs a structured error with correlation ID; expected domain errors → precise 4xx, unexpected → generic 5xx + full log.
- Config through a typed config module validated at boot (fail-fast on missing env), never raw
process.envreads in domain code.
Implementation order (backend dev phases)
- Contract lib first (inputs, types, operations — when the monorepo has one)
- Domain layer in
domain/(services + rules + abstract port contracts) - Adapters in
adapters/(implement the contracts, map errors) - Presentation in
presentation/(resolver/controller per the project's transport choice) - Module wiring (register controller/service + contract-to-adapter binding)
Testing on this stack
- Unit: services tested against in-memory implementations of the abstract repository contracts — the contract being an abstract class makes this trivial. RuleSets are pure functions: table-test every boundary value.
- Integration: real wiring —
Test.createTestingModulewith the real adapter against a real DB (see the matching DB stack skill), or HTTP-level via supertest against the booted app. Do not mock the framework wiring in an integration test (R-TESTI-01). - Contract layer is project-defined — read the host's
docs/ARCHITECTURE.mdfor what carries the contract (ts-rest, OpenAPI, GraphQL schema) and test both sides against it (R-TESTI-03), not via full-stack e2e.
Spec validation checks
Stack-specific checks the spec validators (spec-validate-lead-engineer, on SPEC_<FEATURE>.md §4 API & Domain, §5 Business Rules, §6 Flows) delegate here:
| Check | Severity |
| Domain services follow three-phase orchestration (facts → rules → effects) | BLOCKER |
| RuleSets are pure (no I/O, no closures over ambient state) | BLOCKER |
| Repository contract declared as abstract class; adapter implements it; dependencies point inward | BLOCKER |
Transport convention matches docs/ARCHITECTURE.md (GraphQL code-first vs ts-rest vs REST — never assumed) | BLOCKER |
| Operation names don't collide with the existing API surface | BLOCKER |
| Input validation declared at the edge (Zod or project equivalent) | WARNING |
| Events published post-commit only (not in the write path) | WARNING |
| Sequence diagrams match the three-phase pattern; state diagram covers all enum values from §3 | WARNING |
| Idempotency behavior specified for write endpoints | WARNING |
| Concurrency behavior specified (who wins on conflict) | WARNING |
Live validation commands
R-VAL-01 matrix (backend/domain/contract changes) — exact invocations live in docs/DEV_SETUP.md; obligations:
| Check | Typical shape |
| Type-check affected projects | typecheck target per DEV_SETUP |
| Lint affected projects (boundary rule active) | lint target per DEV_SETUP |
| Run unit + integration tests for affected projects | test target per DEV_SETUP — the load-bearing row |
| If a module was added/edited: boot the API and hit the smoke endpoint | dev target + curl /health per DEV_SETUP |
All rows must pass before commit per .claude/rules/LIVE_VALIDATION.md. Do not weaken type signatures to pass — fix the cause.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

